:
- // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes."
- var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex;
- var match = rgx.exec(semver);
- return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined;
- };
- Object.defineProperty(Semver.prototype, "versionString", {
- get: function () {
- return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch;
- },
- enumerable: true,
- configurable: true
- });
- Semver.prototype.equals = function (sem) {
- return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease;
- };
- Semver.prototype.greaterThan = function (sem) {
- return this.major > sem.major || this.major === sem.major
- && (this.minor > sem.minor || this.minor === sem.minor
- && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease
- && this.patch > sem.patch));
- };
- return Semver;
- }());
- ts.Semver = Semver;
-})(ts || (ts = {}));
var ts;
(function (ts) {
var ScriptSnapshot;
@@ -89377,7 +90273,7 @@ var ts;
if (node.kind === 277 /* SourceFile */) {
return 1 /* Value */;
}
- else if (node.parent.kind === 252 /* ExportAssignment */) {
+ else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) {
return 7 /* All */;
}
else if (isInRightSideOfInternalImportEqualsDeclaration(node)) {
@@ -89993,7 +90889,7 @@ var ts;
ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result)));
return result;
function find(n) {
- if (isNonWhitespaceToken(n)) {
+ if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) {
return n;
}
var children = n.getChildren(sourceFile);
@@ -90011,8 +90907,8 @@ var ts;
isWhiteSpaceOnlyJsxText(child);
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
- return candidate && findRightmostToken(candidate, sourceFile);
+ var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
+ return candidate_2 && findRightmostToken(candidate_2, sourceFile);
}
else {
// candidate should be in this node
@@ -90020,15 +90916,13 @@ var ts;
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
// Here we know that none of child token nodes embrace the position,
// the only known case is when position is at the end of the file.
// Try to find the rightmost token in the file without filtering.
// Namely we are skipping the check: 'position < node.end'
- if (children.length) {
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
- return candidate && findRightmostToken(candidate, sourceFile);
- }
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
+ return candidate && findRightmostToken(candidate, sourceFile);
}
}
ts.findPrecedingToken = findPrecedingToken;
@@ -90250,7 +91144,7 @@ var ts;
function nodeHasTokens(n, sourceFile) {
// If we have a token or node that has a non-zero width, it must have tokens.
// Note: getWidth() does not take trivia into account.
- return n.getWidth(sourceFile) !== 0;
+ return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0;
}
function getNodeModifiers(node) {
var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */;
@@ -90364,7 +91258,7 @@ var ts;
}
ts.createTextSpanFromNode = createTextSpanFromNode;
function createTextRangeFromNode(node, sourceFile) {
- return ts.createTextRange(node.getStart(sourceFile), node.end);
+ return ts.createRange(node.getStart(sourceFile), node.end);
}
ts.createTextRangeFromNode = createTextRangeFromNode;
function createTextSpanFromRange(range) {
@@ -90372,7 +91266,7 @@ var ts;
}
ts.createTextSpanFromRange = createTextSpanFromRange;
function createTextRangeFromSpan(span) {
- return ts.createTextRange(span.start, span.start + span.length);
+ return ts.createRange(span.start, span.start + span.length);
}
ts.createTextRangeFromSpan = createTextRangeFromSpan;
function createTextChangeFromStartLength(start, length, newText) {
@@ -91273,7 +92167,7 @@ var ts;
var lastEnd = 0;
for (var i = 0; i < dense.length; i += 3) {
var start = dense[i];
- var length_6 = dense[i + 1];
+ var length_5 = dense[i + 1];
var type = dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
@@ -91282,8 +92176,8 @@ var ts;
entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
}
}
- entries.push({ length: length_6, classification: convertClassification(type) });
- lastEnd = start + length_6;
+ entries.push({ length: length_5, classification: convertClassification(type) });
+ lastEnd = start + length_5;
}
var whitespaceLength = text.length - lastEnd;
if (whitespaceLength > 0) {
@@ -92040,9 +92934,42 @@ var ts;
}
}
}
+ // check for a version redirect
+ var packageJsonPath = findPackageJson(baseDirectory, host);
+ if (packageJsonPath) {
+ var packageJson = ts.readJson(packageJsonPath, host);
+ var typesVersions = packageJson.typesVersions;
+ if (typeof typesVersions === "object") {
+ var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions);
+ var versionPaths = versionResult && versionResult.paths;
+ var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length);
+ if (versionPaths) {
+ addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host);
+ }
+ }
+ }
}
return result;
}
+ function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) {
+ for (var path in paths) {
+ if (!ts.hasProperty(paths, path))
+ continue;
+ var patterns = paths[path];
+ if (patterns) {
+ var _loop_10 = function (name, kind) {
+ // Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
+ if (!result.some(function (entry) { return entry.name === name; })) {
+ result.push(nameAndKind(name, kind));
+ }
+ };
+ for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
+ var _b = _a[_i], name = _b.name, kind = _b.kind;
+ _loop_10(name, kind);
+ }
+ }
+ }
+ }
/**
* Check all of the declared modules and those in node modules. Possible sources of modules:
* Modules that are found by the type checker
@@ -92056,27 +92983,15 @@ var ts;
var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions);
if (baseUrl) {
var projectDir = compilerOptions.project || host.getCurrentDirectory();
- var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl);
- getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result);
- for (var path in paths) {
- var patterns = paths[path];
- if (paths.hasOwnProperty(path) && patterns) {
- var _loop_11 = function (name, kind) {
- // Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
- if (!result.some(function (entry) { return entry.name === name; })) {
- result.push(nameAndKind(name, kind));
- }
- };
- for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) {
- var _b = _a[_i], name = _b.name, kind = _b.kind;
- _loop_11(name, kind);
- }
- }
+ var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl));
+ getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result);
+ if (paths) {
+ addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host);
}
}
var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
- for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) {
- var ambientName = _d[_c];
+ for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) {
+ var ambientName = _a[_i];
result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */));
}
getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result);
@@ -92085,15 +93000,15 @@ var ts;
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_12 = function (moduleName) {
+ var _loop_11 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */));
}
};
- for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) {
- var moduleName = _f[_e];
- _loop_12(moduleName);
+ for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
+ var moduleName = _c[_b];
+ _loop_11(moduleName);
}
}
if (!foundGlobal) {
@@ -92202,7 +93117,7 @@ var ts;
if (options.types) {
for (var _i = 0, _a = options.types; _i < _a.length; _i++) {
var typesName = _a[_i];
- var moduleName = ts.getUnmangledNameForScopedPackage(typesName);
+ var moduleName = ts.unmangleScopedPackageName(typesName);
pushResult(moduleName);
}
}
@@ -92235,7 +93150,7 @@ var ts;
var typeDirectory = directories_2[_i];
typeDirectory = ts.normalizePath(typeDirectory);
var directoryName = ts.getBaseFileName(typeDirectory);
- var moduleName = ts.getUnmangledNameForScopedPackage(directoryName);
+ var moduleName = ts.unmangleScopedPackageName(directoryName);
pushResult(moduleName);
}
}
@@ -92259,6 +93174,18 @@ var ts;
});
return paths;
}
+ function findPackageJson(directory, host) {
+ var packageJson;
+ ts.forEachAncestorDirectory(directory, function (ancestor) {
+ if (ancestor === "node_modules")
+ return true;
+ packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json");
+ if (packageJson) {
+ return true; // break out
+ }
+ });
+ return packageJson;
+ }
function enumerateNodeModulesVisibleToScript(host, scriptPath) {
if (!host.readFile || !host.fileExists)
return ts.emptyArray;
@@ -92366,11 +93293,12 @@ var ts;
var KeywordCompletionFilters;
(function (KeywordCompletionFilters) {
KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None";
- KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords";
- KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords";
- KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords";
- KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords";
- KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All";
+ KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords";
})(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
var GlobalsSearch;
(function (GlobalsSearch) {
@@ -92479,19 +93407,20 @@ var ts;
}
getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap);
}
- // TODO add filter for keyword based on type/value/namespace and also location
- // Add all keywords if
- // - this is not a member completion list (all the keywords)
- // - other filters are enabled in required scenario so add those keywords
- var isMemberCompletion = isMemberCompletionKind(completionKind);
- if (keywordFilters !== 0 /* None */ || !isMemberCompletion) {
- ts.addRange(entries, getKeywordCompletions(keywordFilters));
+ if (keywordFilters !== 0 /* None */) {
+ var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
+ for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) {
+ var keywordEntry = _a[_i];
+ if (!entryNames.has(keywordEntry.name)) {
+ entries.push(keywordEntry);
+ }
+ }
}
- for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) {
- var literal = literals_1[_i];
+ for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) {
+ var literal = literals_1[_b];
entries.push(createCompletionEntryForLiteral(literal));
}
- return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
+ return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
}
function isUncheckedFile(sourceFile, compilerOptions) {
return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions);
@@ -92513,7 +93442,7 @@ var ts;
return;
}
var realName = ts.unescapeLeadingUnderscores(name);
- if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) {
+ if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) {
entries.push({
name: realName,
kind: "warning" /* warning */,
@@ -92578,6 +93507,9 @@ var ts;
};
}
function quote(text, preferences) {
+ if (/^\d+$/.test(text)) {
+ return text;
+ }
var quoted = JSON.stringify(text);
switch (preferences.quotePreference) {
case undefined:
@@ -93150,7 +94082,10 @@ var ts;
break;
case 71 /* Identifier */:
// For `` we don't want to treat this as a jsx inializer, instead it's the attribute name.
+ if (parent !== previousToken.parent &&
+ !parent.initializer &&
+ ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) {
isJsxInitializer = previousToken;
}
}
@@ -93172,6 +94107,7 @@ var ts;
tryGetGlobalSymbols();
symbols = tagSymbols.concat(symbols);
completionKind = 3 /* MemberLike */;
+ keywordFilters = 0 /* None */;
}
else if (isStartingCloseTag) {
var tagName = contextToken.parent.parent.openingElement.tagName;
@@ -93180,6 +94116,7 @@ var ts;
symbols = [tagSymbol];
}
completionKind = 3 /* MemberLike */;
+ keywordFilters = 0 /* None */;
}
else {
// For JavaScript or TypeScript, if we're not after a dot, then just try to get the
@@ -93317,7 +94254,7 @@ var ts;
// Declaring new property/method/accessor
isNewIdentifierLocation = true;
// Has keywords for constructor parameter
- keywordFilters = 3 /* ConstructorParameterKeywords */;
+ keywordFilters = 4 /* ConstructorParameterKeywords */;
return 1 /* Success */;
}
function tryGetJsxCompletionSymbols() {
@@ -93332,9 +94269,7 @@ var ts;
return 1 /* Success */;
}
function getGlobalCompletions() {
- if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) {
- keywordFilters = 4 /* FunctionLikeBodyKeywords */;
- }
+ keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */;
// Get all entities in the current scope.
completionKind = 1 /* Global */;
isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
@@ -93371,7 +94306,7 @@ var ts;
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
isInSnippetScope = isSnippetScope(scopeNode);
- var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
+ var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) {
@@ -93423,7 +94358,7 @@ var ts;
var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
if (isTypeOnlyCompletion)
- keywordFilters = 5 /* TypeKeywords */;
+ keywordFilters = 6 /* TypeKeywords */;
ts.filterMutate(symbols, function (symbol) {
if (!ts.isSourceFile(location)) {
// export = /**/ here we want to get all meanings, so any symbol is ok
@@ -93444,7 +94379,7 @@ var ts;
}
}
// expressions are value space (which includes the value namespaces)
- return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */);
+ return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */);
});
}
function isContextTokenValueLocation(contextToken) {
@@ -93474,7 +94409,7 @@ var ts;
symbol = symbol.exportSymbol || symbol;
// This is an alias, follow what it aliases
symbol = ts.skipAlias(symbol, typeChecker);
- if (symbol.flags & 67901928 /* Type */) {
+ if (symbol.flags & 67897832 /* Type */) {
return true;
}
if (symbol.flags & 1536 /* Module */) {
@@ -93498,6 +94433,13 @@ var ts;
if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) {
return;
}
+ if (resolvedModuleSymbol !== moduleSymbol &&
+ // Don't add another completion for `export =` of a symbol that's already global.
+ // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`.
+ resolvedModuleSymbol.declarations.some(function (d) { return !!d.getSourceFile().externalModuleIndicator; })) {
+ symbols.push(resolvedModuleSymbol);
+ symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false };
+ }
for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) {
var symbol = _a[_i];
// Don't add a completion for a re-export, only for the original.
@@ -93733,7 +94675,8 @@ var ts;
completionKind = 3 /* MemberLike */;
// Declaring new property/method/accessor
isNewIdentifierLocation = true;
- keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */;
+ keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ :
+ ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */;
// If you're in an interface you don't want to repeat things from super-interface. So just stop here.
if (!ts.isClassLike(decl))
return 1 /* Success */;
@@ -93767,14 +94710,16 @@ var ts;
*/
function tryGetObjectLikeCompletionContainer(contextToken) {
if (contextToken) {
+ var parent = contextToken.parent;
switch (contextToken.kind) {
case 17 /* OpenBraceToken */: // const x = { |
case 26 /* CommaToken */: // const x = { a: 0, |
- var parent = contextToken.parent;
if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) {
return parent;
}
break;
+ case 39 /* AsteriskToken */:
+ return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined;
}
}
return undefined;
@@ -93928,10 +94873,7 @@ var ts;
containingNodeKind === 249 /* NamespaceImport */;
case 125 /* GetKeyword */:
case 136 /* SetKeyword */:
- if (isFromObjectTypeDeclaration(contextToken)) {
- return false;
- }
- // falls through
+ return !isFromObjectTypeDeclaration(contextToken);
case 75 /* ClassKeyword */:
case 83 /* EnumKeyword */:
case 109 /* InterfaceKeyword */:
@@ -93943,6 +94885,8 @@ var ts;
case 116 /* YieldKeyword */:
case 139 /* TypeKeyword */: // type htm|
return true;
+ case 39 /* AsteriskToken */:
+ return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent);
}
// If the previous token is keyword correspoding to class member completion keyword
// there will be completion available here
@@ -94151,17 +95095,19 @@ var ts;
var kind = ts.stringToToken(entry.name);
switch (keywordFilter) {
case 0 /* None */:
- // "undefined" is a global variable, so don't need a keyword completion for it.
- return kind !== 140 /* UndefinedKeyword */;
- case 1 /* ClassElementKeywords */:
+ return false;
+ case 1 /* All */:
+ return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */
+ || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */;
+ case 2 /* ClassElementKeywords */:
return isClassMemberCompletionKeyword(kind);
- case 2 /* InterfaceElementKeywords */:
+ case 3 /* InterfaceElementKeywords */:
return isInterfaceOrTypeLiteralCompletionKeyword(kind);
- case 3 /* ConstructorParameterKeywords */:
+ case 4 /* ConstructorParameterKeywords */:
return ts.isParameterPropertyModifier(kind);
- case 4 /* FunctionLikeBodyKeywords */:
+ case 5 /* FunctionLikeBodyKeywords */:
return isFunctionLikeBodyKeyword(kind);
- case 5 /* TypeKeywords */:
+ case 6 /* TypeKeywords */:
return ts.isTypeKeyword(kind);
default:
return ts.Debug.assertNever(keywordFilter);
@@ -94184,7 +95130,7 @@ var ts;
}
}
function isFunctionLikeBodyKeyword(kind) {
- return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind);
+ return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind);
}
function keywordForNode(node) {
return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind;
@@ -94256,7 +95202,7 @@ var ts;
if (!isFromObjectTypeDeclaration(contextToken))
return undefined;
var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword;
- return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217
+ return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217
? contextToken.parent.parent : undefined;
}
}
@@ -94795,7 +95741,7 @@ var ts;
function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
var entry = bucket.get(path);
- var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target;
+ var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */;
if (!entry && externalCache) {
var sourceFile = externalCache.getDocument(key, path);
if (sourceFile) {
@@ -94809,7 +95755,7 @@ var ts;
}
if (!entry) {
// Have never seen this file with these settings. Create a new source file for it.
- var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217
+ var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
if (externalCache) {
externalCache.setDocument(key, path, sourceFile);
}
@@ -95161,8 +96107,8 @@ var ts;
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var referencingFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
+ var referencingFile = sourceFiles_3[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
if (searchSourceFile.kind === 277 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
@@ -95192,8 +96138,8 @@ var ts;
/** Returns a map from a module symbol Id to all import statements that directly reference the module. */
function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
var map = ts.createMap();
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var sourceFile = sourceFiles_4[_i];
if (cancellationToken)
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
@@ -95457,6 +96403,14 @@ var ts;
(function (ts) {
var FindAllReferences;
(function (FindAllReferences) {
+ var DefinitionKind;
+ (function (DefinitionKind) {
+ DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol";
+ DefinitionKind[DefinitionKind["Label"] = 1] = "Label";
+ DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword";
+ DefinitionKind[DefinitionKind["This"] = 3] = "This";
+ DefinitionKind[DefinitionKind["String"] = 4] = "String";
+ })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {}));
function nodeEntry(node, isInString) {
return { type: "node", node: node.name || node, isInString: isInString };
}
@@ -95490,9 +96444,9 @@ var ts;
// If invoked directly on a shorthand property assignment, then return
// the declaration of the symbol being assigned (not the symbol being assigned to).
if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) {
- var result_6 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); });
- return result_6;
+ var result_7 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); });
+ return result_7;
}
else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -95521,28 +96475,28 @@ var ts;
function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
var info = (function () {
switch (def.type) {
- case "symbol": {
+ case 0 /* Symbol */: {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
var name_3 = displayParts_1.map(function (p) { return p.text; }).join("");
return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 };
}
- case "label": {
+ case 1 /* Label */: {
var node_3 = def.node;
return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
}
- case "keyword": {
+ case 2 /* Keyword */: {
var node_4 = def.node;
var name_4 = ts.tokenToString(node_4.kind);
return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] };
}
- case "this": {
+ case 3 /* This */: {
var node_5 = def.node;
var symbol = checker.getSymbolAtLocation(node_5);
var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")];
return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
- case "string": {
+ case 4 /* String */: {
var node_6 = def.node;
return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
}
@@ -95571,7 +96525,7 @@ var ts;
textSpan: getTextSpan(node, sourceFile),
isWriteAccess: isWriteAccessForReference(node),
isDefinition: node.kind === 79 /* DefaultKeyword */
- || ts.isAnyDeclarationName(node)
+ || !!ts.getDeclarationFromName(node)
|| ts.isLiteralComputedPropertyDeclarationName(node),
isInString: isInString,
};
@@ -95635,7 +96589,62 @@ var ts;
}
/** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
function isWriteAccessForReference(node) {
- return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node);
+ var decl = ts.getDeclarationFromName(node);
+ return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node);
+ }
+ /**
+ * True if 'decl' provides a value, as in `function f() {}`;
+ * false if 'decl' is just a location for a future write, as in 'let x;'
+ */
+ function declarationIsWriteAccess(decl) {
+ // Consider anything in an ambient declaration to be a write access since it may be coming from JS.
+ if (!!(decl.flags & 4194304 /* Ambient */))
+ return true;
+ switch (decl.kind) {
+ case 202 /* BinaryExpression */:
+ case 184 /* BindingElement */:
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ case 79 /* DefaultKeyword */:
+ case 241 /* EnumDeclaration */:
+ case 276 /* EnumMember */:
+ case 255 /* ExportSpecifier */:
+ case 248 /* ImportClause */: // default import
+ case 246 /* ImportEqualsDeclaration */:
+ case 251 /* ImportSpecifier */:
+ case 239 /* InterfaceDeclaration */:
+ case 295 /* JSDocCallbackTag */:
+ case 302 /* JSDocTypedefTag */:
+ case 265 /* JsxAttribute */:
+ case 242 /* ModuleDeclaration */:
+ case 245 /* NamespaceExportDeclaration */:
+ case 249 /* NamespaceImport */:
+ case 149 /* Parameter */:
+ case 274 /* ShorthandPropertyAssignment */:
+ case 240 /* TypeAliasDeclaration */:
+ case 148 /* TypeParameter */:
+ return true;
+ case 273 /* PropertyAssignment */:
+ // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.)
+ return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent);
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
+ case 155 /* Constructor */:
+ case 154 /* MethodDeclaration */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ return !!decl.body;
+ case 235 /* VariableDeclaration */:
+ case 152 /* PropertyDeclaration */:
+ return !!decl.initializer || ts.isCatchClause(decl.parent);
+ case 153 /* MethodSignature */:
+ case 151 /* PropertySignature */:
+ case 303 /* JSDocPropertyTag */:
+ case 297 /* JSDocParameterTag */:
+ return false;
+ default:
+ return ts.Debug.failBadSyntaxKind(decl);
+ }
}
})(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
})(ts || (ts = {}));
@@ -95725,7 +96734,7 @@ var ts;
ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
- return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray;
+ return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray;
}
/** getReferencedSymbols for special node kinds. */
function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
@@ -95894,7 +96903,7 @@ var ts;
var references = this.symbolIdToReferences[symbolId];
if (!references) {
references = this.symbolIdToReferences[symbolId] = [];
- this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references });
+ this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references });
}
return function (node) { return references.push(FindAllReferences.nodeEntry(node)); };
};
@@ -96062,8 +97071,8 @@ var ts;
return undefined;
}
var scope;
- for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
- var declaration = declarations_10[_i];
+ for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
+ var declaration = declarations_11[_i];
var container = ts.getContainerNode(declaration);
if (scope && scope !== container) {
// Different declarations have different containers, bail out
@@ -96112,8 +97121,8 @@ var ts;
if (!signature.name || !ts.isIdentifier(signature.name))
return;
var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
- for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
- var sourceFile = sourceFiles_7[_i];
+ for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
+ var sourceFile = sourceFiles_5[_i];
for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) {
var name = _b[_a];
if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
@@ -96170,7 +97179,7 @@ var ts;
// Only pick labels that are either the target label, or have a target that is the target label
return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined;
});
- return [{ definition: { type: "label", node: targetLabel }, references: references }];
+ return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }];
}
function isValidReferencePosition(node, searchSymbolName) {
// Compare the length so we filter out strict superstrings of the symbol we are looking for
@@ -96197,7 +97206,7 @@ var ts;
return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined;
});
});
- return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined;
+ return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined;
}
function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) {
if (addReferencesHere === void 0) { addReferencesHere = true; }
@@ -96602,7 +97611,7 @@ var ts;
// and has the same static qualifier as the original 'super's owner.
return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined;
});
- return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }];
+ return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }];
}
function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false);
@@ -96660,8 +97669,9 @@ var ts;
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
+ var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; });
return [{
- definition: { type: "this", node: thisOrSuperKeyword },
+ definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword },
references: references
}];
}
@@ -96673,7 +97683,7 @@ var ts;
});
});
return [{
- definition: { type: "string", node: node },
+ definition: { type: 4 /* String */, node: node },
references: references
}];
}
@@ -96777,8 +97787,8 @@ var ts;
// To achieve that we will keep iterating until the result stabilizes.
// Remember the last meaning
lastIterationMeaning = meaning;
- for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
- var declaration = declarations_11[_i];
+ for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
+ var declaration = declarations_12[_i];
var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
if (declarationMeaning & meaning) {
meaning |= declarationMeaning;
@@ -96840,14 +97850,14 @@ var ts;
/* @internal */
var ts;
(function (ts) {
- function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) {
+ function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) {
var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host);
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper);
var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper);
return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) {
updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames);
- updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences);
+ updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName);
});
}
ts.getEditsForFileRename = getEditsForFileRename;
@@ -96943,9 +97953,9 @@ var ts;
return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames);
}
}
- function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) {
+ function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
var allFiles = program.getSourceFiles();
- var _loop_13 = function (sourceFile) {
+ var _loop_12 = function (sourceFile) {
var newFromOld = oldToNew(sourceFile.path);
var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
@@ -96971,13 +97981,13 @@ var ts;
: getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
// Need an update if the imported file moved, or the importing file moved and was using a relative path.
return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text)))
- ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap)
+ ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text)
: undefined;
});
};
for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
var sourceFile = allFiles_1[_i];
- _loop_13(sourceFile);
+ _loop_12(sourceFile);
}
}
function combineNormal(pathA, pathB) {
@@ -97010,7 +98020,7 @@ var ts;
}
}
function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) {
- for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) {
+ for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162
var ref = _a[_i];
var updated = updateRef(ref.fileName);
if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end))
@@ -97024,7 +98034,7 @@ var ts;
}
}
function createStringRange(node, sourceFile) {
- return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1);
+ return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1);
}
function forEachProperty(objectLiteral, cb) {
if (!ts.isObjectLiteralExpression(objectLiteral))
@@ -97066,7 +98076,7 @@ var ts;
}
var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
// Don't go to the component constructor definition for a JSX element, just go to the component definition.
- if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) {
+ if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) {
var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
// For a function, if this is the original function definition, return just sigInfo.
// If this is the original constructor definition, parent is the class.
@@ -97332,6 +98342,16 @@ var ts;
// Don't go to a function type, go to the value having that type.
return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); });
}
+ function isConstructorLike(node) {
+ switch (node.kind) {
+ case 155 /* Constructor */:
+ case 164 /* ConstructorType */:
+ case 159 /* ConstructSignature */:
+ return true;
+ default:
+ return false;
+ }
+ }
})(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {}));
})(ts || (ts = {}));
/* @internal */
@@ -97741,7 +98761,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_14 = function (sourceFile) {
+ var _loop_13 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && sourceFile.isDeclarationFile) {
return "continue";
@@ -97751,9 +98771,9 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) {
- var sourceFile = sourceFiles_8[_i];
- _loop_14(sourceFile);
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
+ _loop_13(sourceFile);
}
rawItems.sort(compareNavigateToItems);
return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
@@ -97766,8 +98786,8 @@ var ts;
if (!match) {
return; // continue to next named declarations
}
- for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
- var declaration = declarations_12[_i];
+ for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) {
+ var declaration = declarations_13[_i];
if (!shouldKeepItem(declaration, checker))
continue;
if (patternMatcher.patternContainsDots) {
@@ -99248,13 +100268,13 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_15 = function (start) {
+ var _loop_14 = function (start) {
if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
return { value: start };
}
};
for (var start = 0; start <= n; start++) {
- var state_3 = _loop_15(start);
+ var state_3 = _loop_14(start);
if (typeof state_3 === "object")
return state_3.value;
}
@@ -99794,9 +100814,9 @@ var ts;
if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) {
return undefined;
}
- // Can't rename a module name.
- if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node))
- return undefined;
+ if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) {
+ return getRenameInfoForModule(node, sourceFile, symbol);
+ }
var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */)
? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
@@ -99805,9 +100825,28 @@ var ts;
var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol);
return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
}
+ function getRenameInfoForModule(node, sourceFile, moduleSymbol) {
+ var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile);
+ if (!moduleSourceFile)
+ return undefined;
+ var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index");
+ var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex;
+ var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */;
+ return {
+ canRename: true,
+ fileToRename: name,
+ kind: kind,
+ displayName: name,
+ localizedErrorMessage: undefined,
+ fullDisplayName: name,
+ kindModifiers: "" /* none */,
+ triggerSpan: createTriggerSpanForNode(node, sourceFile),
+ };
+ }
function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
return {
canRename: true,
+ fileToRename: undefined,
kind: kind,
displayName: displayName,
localizedErrorMessage: undefined,
@@ -99882,17 +100921,26 @@ var ts;
return undefined;
cancellationToken.throwIfCancellationRequested();
// Extra syntactic and semantic filtering of signature help
- var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners);
+ var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners);
cancellationToken.throwIfCancellationRequested();
if (!candidateInfo) {
// We didn't have any sig help items produced by the TS compiler. If this is a JS
// file, then see if we can figure out anything better.
return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined;
}
- return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); });
+ return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
+ return candidateInfo.kind === 0 /* Candidate */
+ ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker)
+ : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker);
+ });
}
SignatureHelp.getSignatureHelpItems = getSignatureHelpItems;
- function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) {
+ var CandidateOrTypeKind;
+ (function (CandidateOrTypeKind) {
+ CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate";
+ CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type";
+ })(CandidateOrTypeKind || (CandidateOrTypeKind = {}));
+ function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) {
var invocation = _a.invocation, argumentCount = _a.argumentCount;
switch (invocation.kind) {
case 0 /* Call */: {
@@ -99901,17 +100949,21 @@ var ts;
}
var candidates = [];
var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217
- return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature };
+ return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature };
}
case 1 /* TypeArgs */: {
- if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) {
+ var called = invocation.called;
+ if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) {
return undefined;
}
- var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker);
- return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) };
+ var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker);
+ if (candidates.length !== 0)
+ return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) };
+ var symbol = checker.getSymbolAtLocation(called);
+ return symbol && { kind: 1 /* Type */, symbol: symbol };
}
case 2 /* Contextual */:
- return { candidates: [invocation.signature], resolvedSignature: invocation.signature };
+ return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature };
default:
return ts.Debug.assertNever(invocation);
}
@@ -99928,7 +100980,7 @@ var ts;
return !!containingList && ts.contains(invocationChildren, containingList);
}
case 27 /* LessThanToken */:
- return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression);
+ return containsPrecedingToken(startingToken, sourceFile, node.expression);
default:
return false;
}
@@ -99950,9 +101002,9 @@ var ts;
});
});
}
- function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) {
+ function containsPrecedingToken(startingToken, sourceFile, container) {
var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true));
- return ts.rangeContainsRange(calledExpression, precedingToken);
+ return ts.rangeContainsRange(container, precedingToken);
}
function getArgumentInfoForCompletions(node, position, sourceFile) {
var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile);
@@ -100239,7 +101291,7 @@ var ts;
return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile, checker) {
- var _loop_16 = function (n) {
+ var _loop_15 = function (n) {
// If the node is not a subspan of its parent, this is a big problem.
// There have been crashes that might be caused by this violation.
ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); });
@@ -100249,7 +101301,7 @@ var ts;
}
};
for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) {
- var state_4 = _loop_16(n);
+ var state_4 = _loop_15(n);
if (typeof state_4 === "object")
return state_4.value;
}
@@ -100264,10 +101316,13 @@ var ts;
function getExpressionFromInvocation(invocation) {
return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called;
}
+ function getEnclosingDeclarationFromInvocation(invocation) {
+ return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
+ }
var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) {
var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
- var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
+ var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation));
var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray;
var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); });
@@ -100278,11 +101333,28 @@ var ts;
ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function.
return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount };
}
+ function createTypeHelpItems(symbol, _a, sourceFile, checker) {
+ var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
+ var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
+ if (!typeParameters)
+ return undefined;
+ var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)];
+ return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount };
+ }
+ function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) {
+ var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol);
+ var printer = ts.createPrinter({ removeComments: true });
+ var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
+ var documentation = symbol.getDocumentationComment(checker);
+ var tags = symbol.getJsDocTags();
+ var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]);
+ return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
+ }
+ var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()];
function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) {
var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix;
var prefixDisplayParts = callTargetDisplayParts.concat(prefix);
var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker));
- var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()];
var documentation = candidateSignature.getDocumentationComment(checker);
var tags = candidateSignature.getJsDocTags();
return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
@@ -100336,7 +101408,7 @@ var ts;
var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
});
- return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false };
+ return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false };
}
})(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {}));
})(ts || (ts = {}));
@@ -100460,7 +101532,7 @@ var ts;
function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) {
program.getSemanticDiagnostics(sourceFile, cancellationToken);
var diags = [];
- var checker = program.getDiagnosticsProducingTypeChecker();
+ var checker = program.getTypeChecker();
if (sourceFile.commonJsModuleIndicator &&
(ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) &&
containsTopLevelCommonjs(sourceFile)) {
@@ -100564,10 +101636,10 @@ var ts;
}
}
function addConvertToAsyncFunctionDiagnostics(node, checker, diags) {
- var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined;
- if (ts.isAsyncFunction(node) || !node.body || !functionType) {
+ if (ts.isAsyncFunction(node) || !node.body) {
return;
}
+ var functionType = checker.getTypeAtLocation(node);
var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */);
var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined;
if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) {
@@ -100744,13 +101816,16 @@ var ts;
var documentation;
var tags;
var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
- var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location);
+ var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */;
var hasAddedSymbolInfo = false;
- var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location);
+ var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location);
var type;
var printer;
var documentationFromAlias;
var tagsFromAlias;
+ if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) {
+ return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined };
+ }
// Class at constructor site need to be shown as constructor apart from property,method, vars
if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) {
// If it is accessor they are allowed only if location is at name of the accessor
@@ -100888,7 +101963,7 @@ var ts;
addFullSymbolName(symbol);
writeTypeParametersOfSymbol(symbol, sourceFile);
}
- if (symbolFlags & 524288 /* TypeAlias */) {
+ if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) {
prefixNextMeaning();
displayParts.push(ts.keywordPart(139 /* TypeKeyword */));
displayParts.push(ts.spacePart());
@@ -101190,7 +102265,8 @@ var ts;
displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads"));
displayParts.push(ts.punctuationPart(20 /* CloseParenToken */));
}
- documentation = signature.getDocumentationComment(typeChecker);
+ var docComment = signature.getDocumentationComment(typeChecker);
+ documentation = docComment.length === 0 ? undefined : docComment;
tags = signature.getJsDocTags();
}
function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) {
@@ -101330,7 +102406,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_17 = function (opt) {
+ var _loop_16 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -101349,7 +102425,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_17(opt);
+ _loop_16(opt);
}
return options;
}
@@ -104156,7 +105232,7 @@ var ts;
};
ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
if (options === void 0) { options = {}; }
- this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options);
+ this.replaceRange(sourceFile, ts.createRange(pos), newNode, options);
};
ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) {
if (options === void 0) { options = {}; }
@@ -104194,7 +105270,7 @@ var ts;
this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text });
};
ChangeTracker.prototype.insertText = function (sourceFile, pos, text) {
- this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text);
+ this.replaceRangeWithText(sourceFile, ts.createRange(pos), text);
};
/** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) {
@@ -104302,7 +105378,7 @@ var ts;
// check if previous statement ends with semicolon
// if not - insert semicolon to preserve the code from changing the meaning due to ASI
if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) {
- this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */));
+ this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */));
}
}
var endPosition = getAdjustedEndPosition(sourceFile, after, {});
@@ -104427,7 +105503,7 @@ var ts;
}
// write separator and leading trivia of the next element as suffix
var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile));
- this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix });
+ this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix });
}
}
else {
@@ -104459,7 +105535,7 @@ var ts;
}
if (multilineList) {
// insert separator immediately following the 'after' node to preserve comments in trailing trivia
- this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator));
+ this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator));
// use the same indentation as 'after' item
var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options);
// insert element before the line break on the line that contains 'after' element
@@ -104467,10 +105543,10 @@ var ts;
if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) {
insertPos--;
}
- this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter });
+ this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter });
}
else {
- this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
+ this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
}
}
return this;
@@ -104482,14 +105558,14 @@ var ts;
var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1];
// For `class C { }` remove the whitespace inside the braces.
if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) {
- _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1));
+ _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1));
}
});
};
ChangeTracker.prototype.finishDeleteDeclarations = function () {
var _this = this;
var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
- var _loop_18 = function (sourceFile, node) {
+ var _loop_17 = function (sourceFile, node) {
if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
if (ts.isArray(node)) {
this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node));
@@ -104502,7 +105578,7 @@ var ts;
var this_1 = this;
for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node;
- _loop_18(sourceFile, node);
+ _loop_17(sourceFile, node);
}
deletedNodesInLists.forEach(function (node) {
var sourceFile = node.getSourceFile();
@@ -104552,14 +105628,14 @@ var ts;
// order changes by start position
// If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa.
var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); });
- var _loop_19 = function (i) {
+ var _loop_18 = function (i) {
ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () {
return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range);
});
};
// verify that change intervals do not overlap, except possibly at end points.
for (var i = 0; i < normalized.length - 1; i++) {
- _loop_19(i);
+ _loop_18(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -105463,7 +106539,16 @@ var ts;
});
function convertToAsyncFunction(changes, sourceFile, position, checker, context) {
// get the function declaration - returns a promise
- var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position));
+ var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position);
+ var functionToConvert;
+ // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name
+ if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) &&
+ tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) {
+ functionToConvert = tokenAtPosition.parent.initializer;
+ }
+ else {
+ functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration);
+ }
if (!functionToConvert) {
return;
}
@@ -105485,7 +106570,7 @@ var ts;
var newNodes = transformExpression(node, transformer, node);
changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes);
}
- var _loop_20 = function (statement) {
+ var _loop_19 = function (statement) {
if (ts.isCallExpression(statement)) {
startTransformation(statement, statement);
}
@@ -105502,7 +106587,7 @@ var ts;
};
for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
var statement = returnStatements_1[_i];
- _loop_20(statement);
+ _loop_19(statement);
}
}
// Returns the identifiers that are never reassigned in the refactor
@@ -105785,8 +106870,8 @@ var ts;
return ts.createNodeArray(innerCbBody);
}
if (hasPrevArgName && !shouldReturn) {
- var type_3 = transformer.checker.getTypeAtLocation(func);
- var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType();
+ var type_5 = transformer.checker.getTypeAtLocation(func);
+ var returnType_1 = getLastCallSignature(type_5, transformer.checker).getReturnType();
var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer);
prevArgName.types.push(returnType_1);
return varDeclOrAssignment_1;
@@ -105941,7 +107026,7 @@ var ts;
forEachExportReference(sourceFile, function (node) {
var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
- || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) {
+ || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) {
// Unconditionally add an underscore in case `text` is a keyword.
res.set(text, makeUniqueName("_" + text, identifiers));
}
@@ -106058,7 +107143,7 @@ var ts;
return replacement[1];
}
else {
- changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default");
+ changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default");
return true;
}
}
@@ -106544,33 +107629,40 @@ var ts;
ImportKind[ImportKind["Equals"] = 3] = "Equals";
})(ImportKind || (ImportKind = {}));
function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) {
- var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles());
+ var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles());
ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }));
// We sort the best codefixes first, so taking `first` is best for completions.
var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier;
var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences));
- return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) };
+ return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) };
}
codefix.getImportCompletionAction = getImportCompletionAction;
- function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) {
+ function codeFixActionToCodeAction(_a) {
+ var description = _a.description, changes = _a.changes, commands = _a.commands;
+ return { description: description, changes: changes, commands: commands };
+ }
+ function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) {
var result = [];
forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) {
// Don't import from a re-export when looking "up" like to `./index` or `../index`.
if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) {
return;
}
+ var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions);
+ if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) {
+ result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol) });
+ }
for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) {
var exported = _a[_i];
- if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) {
- var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported;
- result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) });
+ if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) {
+ result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) });
}
}
});
return result;
}
function isTypeOnlySymbol(s) {
- return !(s.flags & 67216319 /* Value */);
+ return !(s.flags & 67220415 /* Value */);
}
function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) {
var checker = program.getTypeChecker();
@@ -106641,14 +107733,14 @@ var ts;
var isJs = ts.isSourceFileJavaScript(sourceFile);
var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
- var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap);
- return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) {
+ return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap)
+ .map(function (moduleSpecifier) {
// `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types.
return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind };
- }); });
+ });
});
- // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together
- return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; }));
+ // Sort to keep the shortest paths first
+ return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; });
}
function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) {
var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier);
@@ -106690,7 +107782,7 @@ var ts;
// The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`.
var parent = token.parent;
return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent)
- ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol)
+ ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol)
: undefined;
}
function getUmdImportKind(compilerOptions) {
@@ -106742,13 +107834,9 @@ var ts;
}
forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) {
cancellationToken.throwIfCancellationRequested();
- // check the default export
- var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol);
- if (defaultExport) {
- var info = getDefaultExportInfo(defaultExport, moduleSymbol, program);
- if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) {
- addSymbol(moduleSymbol, defaultExport, 1 /* Default */);
- }
+ var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions());
+ if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) {
+ addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind);
}
// check exports with the same name
var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol);
@@ -106758,7 +107846,22 @@ var ts;
});
return originalSymbolToExportInfos;
}
- function getDefaultExportInfo(defaultExport, moduleSymbol, program) {
+ function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) {
+ var exported = getDefaultLikeExportWorker(moduleSymbol, checker);
+ if (!exported)
+ return undefined;
+ var symbol = exported.symbol, kind = exported.kind;
+ var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions);
+ return info && { symbol: symbol, symbolForMeaning: info.symbolForMeaning, name: info.name, kind: kind };
+ }
+ function getDefaultLikeExportWorker(moduleSymbol, checker) {
+ var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol);
+ if (defaultExport)
+ return { symbol: defaultExport, kind: 1 /* Default */ };
+ var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol);
+ return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ };
+ }
+ function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) {
var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport);
if (localSymbol)
return { symbolForMeaning: localSymbol, name: localSymbol.name };
@@ -106766,11 +107869,11 @@ var ts;
if (name !== undefined)
return { symbolForMeaning: defaultExport, name: name };
if (defaultExport.flags & 2097152 /* Alias */) {
- var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport);
- return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program);
+ var aliased = checker.getImmediateAliasedSymbol(defaultExport);
+ return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions);
}
else {
- return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) };
+ return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) };
}
}
function getNameForExportDefault(symbol) {
@@ -107009,10 +108112,10 @@ var ts;
flags |= 1920 /* Namespace */;
}
if (meaning & 2 /* Type */) {
- flags |= 67901928 /* Type */;
+ flags |= 67897832 /* Type */;
}
if (meaning & 1 /* Value */) {
- flags |= 67216319 /* Value */;
+ flags |= 67220415 /* Value */;
}
return flags;
}
@@ -107080,7 +108183,7 @@ var ts;
});
typeDeclToMembers.forEach(function (infos, classDeclaration) {
var supers = getAllSupers(classDeclaration, checker);
- var _loop_21 = function (info) {
+ var _loop_20 = function (info) {
// If some superclass added this property, don't add it again.
if (supers.some(function (superClassOrInterface) {
var superInfos = typeDeclToMembers.get(superClassOrInterface);
@@ -107107,7 +108210,7 @@ var ts;
};
for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
var info = infos_1[_i];
- _loop_21(info);
+ _loop_20(info);
}
});
}));
@@ -107308,7 +108411,7 @@ var ts;
}
function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) {
var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text;
- var packageName = ts.getPackageName(moduleName).packageName;
+ var packageName = ts.parsePackageName(moduleName).packageName;
return diagCode === errorCodeCannotFindModule
? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined)
: (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217
@@ -108177,22 +109280,19 @@ var ts;
signatureDeclaration.body = body;
return signatureDeclaration;
}
- function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) {
- var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent;
+ function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) {
+ var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent;
var checker = context.program.getTypeChecker();
var types = ts.map(args, function (arg) {
- var type = checker.getTypeAtLocation(arg);
- if (type === undefined) {
- return undefined;
- }
// Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
- type = checker.getBaseTypeOfLiteralType(type);
- return checker.typeToTypeNode(type);
+ return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)));
});
var names = ts.map(args, function (arg) {
return ts.isIdentifier(arg) ? arg.text :
ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined;
});
+ var contextualType = checker.getContextualType(call);
+ var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */);
return ts.createMethod(
/*decorators*/ undefined,
/*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined,
@@ -108202,7 +109302,7 @@ var ts;
return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i);
}),
/*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs),
- /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined);
+ /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined);
}
codefix.createMethodFromCallExpression = createMethodFromCallExpression;
function createDummyParameters(argCount, names, types, minArgumentCount, inJs) {
@@ -108750,16 +109850,18 @@ var ts;
else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) {
return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker));
}
- else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) {
+ else if (usageContext.numberIndexContext) {
+ return checker.createArrayType(recur(usageContext.numberIndexContext));
+ }
+ else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
var members_6 = ts.createUnderscoreEscapedMap();
var callSignatures = [];
var constructSignatures = [];
var stringIndexInfo = void 0;
- var numberIndexInfo = void 0;
if (usageContext.properties) {
usageContext.properties.forEach(function (context, name) {
var symbol = checker.createSymbol(4 /* Property */, name);
- symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType();
+ symbol.type = recur(context);
members_6.set(name, symbol);
});
}
@@ -108775,17 +109877,17 @@ var ts;
constructSignatures.push(getSignatureFromCallContext(constructContext, checker));
}
}
- if (usageContext.numberIndexContext) {
- numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false);
- }
if (usageContext.stringIndexContext) {
- stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false);
+ stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false);
}
- return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217
+ return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217
}
else {
return undefined;
}
+ function recur(innerContext) {
+ return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType();
+ }
}
function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) {
var types = [];
@@ -109481,7 +110583,7 @@ var ts;
});
var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
var neededNamedImports = [];
- var _loop_22 = function (element) {
+ var _loop_21 = function (element) {
var propertyName = (element.propertyName || element.name).text;
ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
@@ -109500,7 +110602,7 @@ var ts;
};
for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
var element = _a[_i];
- _loop_22(element);
+ _loop_21(element);
}
changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
if (neededNamedImports.length) {
@@ -110732,7 +111834,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_23 = function (i) {
+ var _loop_22 = function (i) {
var scopeUsages = usagesPerScope[i];
// Special case: in the innermost scope, all usages are available.
// (The computed value reflects the value at the top-level of the scope, but the
@@ -110772,7 +111874,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_23(i);
+ _loop_22(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function isInGenericContext(node) {
@@ -111322,10 +112424,10 @@ var ts;
}
function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
var checker = program.getTypeChecker();
- var _loop_24 = function (sourceFile) {
+ var _loop_23 = function (sourceFile) {
if (sourceFile === oldFile)
return "continue";
- var _loop_25 = function (statement) {
+ var _loop_24 = function (statement) {
forEachImportInStatement(statement, function (importNode) {
if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
return;
@@ -111347,12 +112449,12 @@ var ts;
};
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
- _loop_25(statement);
+ _loop_24(statement);
}
};
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- _loop_24(sourceFile);
+ _loop_23(sourceFile);
}
}
function getNamespaceLikeImport(node) {
@@ -112344,8 +113446,8 @@ var ts;
return ts.emptyArray;
var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations);
if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
- for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) {
- var declaration = declarations_13[_i];
+ for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) {
+ var declaration = declarations_14[_i];
var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217
// TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
if (inheritedDocs)
@@ -113082,14 +114184,14 @@ var ts;
var typeChecker = program.getTypeChecker();
var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker);
if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
- var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
- return type_4 && {
+ var type_6 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
+ return type_6 && {
kind: "" /* unknown */,
kindModifiers: "" /* none */,
textSpan: ts.createTextSpanFromNode(node, sourceFile),
- displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }),
- documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined
+ displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_6, ts.getContainerNode(node)); }),
+ documentation: type_6.symbol ? type_6.symbol.getDocumentationComment(typeChecker) : undefined,
+ tags: type_6.symbol ? type_6.symbol.getJsDocTags() : undefined
};
}
var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js
index dd81fe55ced..1661ac81e22 100644
--- a/lib/typingsInstaller.js
+++ b/lib/typingsInstaller.js
@@ -88,7 +88,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "3.1";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".0-rc";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -101,6 +101,7 @@ var ts;
})(ts || (ts = {}));
/* @internal */
(function (ts) {
+ ts.emptyArray = [];
/** Create a MapLike with good performance. */
function createDictionaryObject() {
var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword
@@ -729,17 +730,23 @@ var ts;
}
return result;
}
+ /**
+ * Deduplicates an unsorted array.
+ * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param comparer An optional `Comparer` used to sort entries before comparison, though the
+ * result will remain in the original order in `array`.
+ */
function deduplicate(array, equalityComparer, comparer) {
- return !array ? undefined :
- array.length === 0 ? [] :
- array.length === 1 ? array.slice() :
- comparer ? deduplicateRelational(array, equalityComparer, comparer) :
- deduplicateEquality(array, equalityComparer);
+ return array.length === 0 ? [] :
+ array.length === 1 ? array.slice() :
+ comparer ? deduplicateRelational(array, equalityComparer, comparer) :
+ deduplicateEquality(array, equalityComparer);
}
ts.deduplicate = deduplicate;
+ /**
+ * Deduplicates an array that has already been sorted.
+ */
function deduplicateSorted(array, comparer) {
- if (!array)
- return undefined;
if (array.length === 0)
return [];
var last = array[0];
@@ -1161,7 +1168,7 @@ var ts;
return false;
for (var key in left) {
if (hasOwnProperty.call(left, key)) {
- if (!hasOwnProperty.call(right, key) === undefined)
+ if (!hasOwnProperty.call(right, key))
return false;
if (!equalityComparer(left[key], right[key]))
return false;
@@ -2042,6 +2049,366 @@ var ts;
performance.disable = disable;
})(performance = ts.performance || (ts.performance = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ // https://semver.org/#spec-item-2
+ // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
+ // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
+ // > version, and Z is the patch version. Each element MUST increase numerically.
+ //
+ // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
+ // value of `0`.
+ var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
+ // https://semver.org/#spec-item-9
+ // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
+ // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
+ // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
+ // > MUST NOT include leading zeroes.
+ var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
+ // https://semver.org/#spec-item-10
+ // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
+ // > identifiers immediately following the patch or pre-release version. Identifiers MUST
+ // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
+ var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
+ // https://semver.org/#spec-item-9
+ // > Numeric identifiers MUST NOT include leading zeroes.
+ var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
+ /**
+ * Describes a precise semantic version number, https://semver.org
+ */
+ var Version = /** @class */ (function () {
+ function Version(major, minor, patch, prerelease, build) {
+ if (minor === void 0) { minor = 0; }
+ if (patch === void 0) { patch = 0; }
+ if (prerelease === void 0) { prerelease = ""; }
+ if (build === void 0) { build = ""; }
+ if (typeof major === "string") {
+ var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version");
+ (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
+ }
+ ts.Debug.assert(major >= 0, "Invalid argument: major");
+ ts.Debug.assert(minor >= 0, "Invalid argument: minor");
+ ts.Debug.assert(patch >= 0, "Invalid argument: patch");
+ ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
+ ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
+ this.major = major;
+ this.minor = minor;
+ this.patch = patch;
+ this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
+ this.build = build ? build.split(".") : ts.emptyArray;
+ }
+ Version.tryParse = function (text) {
+ var result = tryParseComponents(text);
+ if (!result)
+ return undefined;
+ var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
+ return new Version(major, minor, patch, prerelease, build);
+ };
+ Version.prototype.compareTo = function (other) {
+ // https://semver.org/#spec-item-11
+ // > Precedence is determined by the first difference when comparing each of these
+ // > identifiers from left to right as follows: Major, minor, and patch versions are
+ // > always compared numerically.
+ //
+ // https://semver.org/#spec-item-11
+ // > Precedence for two pre-release versions with the same major, minor, and patch version
+ // > MUST be determined by comparing each dot separated identifier from left to right until
+ // > a difference is found [...]
+ //
+ // https://semver.org/#spec-item-11
+ // > Build metadata does not figure into precedence
+ if (this === other)
+ return 0 /* EqualTo */;
+ if (other === undefined)
+ return 1 /* GreaterThan */;
+ return ts.compareValues(this.major, other.major)
+ || ts.compareValues(this.minor, other.minor)
+ || ts.compareValues(this.patch, other.patch)
+ || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
+ };
+ Version.prototype.increment = function (field) {
+ switch (field) {
+ case "major": return new Version(this.major + 1, 0, 0);
+ case "minor": return new Version(this.major, this.minor + 1, 0);
+ case "patch": return new Version(this.major, this.minor, this.patch + 1);
+ default: return ts.Debug.assertNever(field);
+ }
+ };
+ Version.prototype.toString = function () {
+ var result = this.major + "." + this.minor + "." + this.patch;
+ if (ts.some(this.prerelease))
+ result += "-" + this.prerelease.join(".");
+ if (ts.some(this.build))
+ result += "+" + this.build.join(".");
+ return result;
+ };
+ Version.zero = new Version(0, 0, 0);
+ return Version;
+ }());
+ ts.Version = Version;
+ function tryParseComponents(text) {
+ var match = versionRegExp.exec(text);
+ if (!match)
+ return undefined;
+ var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d;
+ if (prerelease && !prereleaseRegExp.test(prerelease))
+ return undefined;
+ if (build && !buildRegExp.test(build))
+ return undefined;
+ return {
+ major: parseInt(major, 10),
+ minor: parseInt(minor, 10),
+ patch: parseInt(patch, 10),
+ prerelease: prerelease,
+ build: build
+ };
+ }
+ function comparePrerelaseIdentifiers(left, right) {
+ // https://semver.org/#spec-item-11
+ // > When major, minor, and patch are equal, a pre-release version has lower precedence
+ // > than a normal version.
+ if (left === right)
+ return 0 /* EqualTo */;
+ if (left.length === 0)
+ return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
+ if (right.length === 0)
+ return -1 /* LessThan */;
+ // https://semver.org/#spec-item-11
+ // > Precedence for two pre-release versions with the same major, minor, and patch version
+ // > MUST be determined by comparing each dot separated identifier from left to right until
+ // > a difference is found [...]
+ var length = Math.min(left.length, right.length);
+ for (var i = 0; i < length; i++) {
+ var leftIdentifier = left[i];
+ var rightIdentifier = right[i];
+ if (leftIdentifier === rightIdentifier)
+ continue;
+ var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
+ var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
+ if (leftIsNumeric || rightIsNumeric) {
+ // https://semver.org/#spec-item-11
+ // > Numeric identifiers always have lower precedence than non-numeric identifiers.
+ if (leftIsNumeric !== rightIsNumeric)
+ return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
+ // https://semver.org/#spec-item-11
+ // > identifiers consisting of only digits are compared numerically
+ var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
+ if (result)
+ return result;
+ }
+ else {
+ // https://semver.org/#spec-item-11
+ // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
+ var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
+ if (result)
+ return result;
+ }
+ }
+ // https://semver.org/#spec-item-11
+ // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
+ // > of the preceding identifiers are equal.
+ return ts.compareValues(left.length, right.length);
+ }
+ /**
+ * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
+ */
+ var VersionRange = /** @class */ (function () {
+ function VersionRange(spec) {
+ this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
+ }
+ VersionRange.tryParse = function (text) {
+ var sets = parseRange(text);
+ if (sets) {
+ var range = new VersionRange("");
+ range._alternatives = sets;
+ return range;
+ }
+ return undefined;
+ };
+ VersionRange.prototype.test = function (version) {
+ if (typeof version === "string")
+ version = new Version(version);
+ return testDisjunction(version, this._alternatives);
+ };
+ VersionRange.prototype.toString = function () {
+ return formatDisjunction(this._alternatives);
+ };
+ return VersionRange;
+ }());
+ ts.VersionRange = VersionRange;
+ // https://github.com/npm/node-semver#range-grammar
+ //
+ // range-set ::= range ( logical-or range ) *
+ // range ::= hyphen | simple ( ' ' simple ) * | ''
+ // logical-or ::= ( ' ' ) * '||' ( ' ' ) *
+ var logicalOrRegExp = /\s*\|\|\s*/g;
+ var whitespaceRegExp = /\s+/g;
+ // https://github.com/npm/node-semver#range-grammar
+ //
+ // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
+ // xr ::= 'x' | 'X' | '*' | nr
+ // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
+ // qualifier ::= ( '-' pre )? ( '+' build )?
+ // pre ::= parts
+ // build ::= parts
+ // parts ::= part ( '.' part ) *
+ // part ::= nr | [-0-9A-Za-z]+
+ var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
+ // https://github.com/npm/node-semver#range-grammar
+ //
+ // hyphen ::= partial ' - ' partial
+ var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
+ // https://github.com/npm/node-semver#range-grammar
+ //
+ // simple ::= primitive | partial | tilde | caret
+ // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
+ // tilde ::= '~' partial
+ // caret ::= '^' partial
+ var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
+ function parseRange(text) {
+ var alternatives = [];
+ for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
+ var range = _a[_i];
+ if (!range)
+ continue;
+ var comparators = [];
+ var match = hyphenRegExp.exec(range);
+ if (match) {
+ if (!parseHyphen(match[1], match[2], comparators))
+ return undefined;
+ }
+ else {
+ for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
+ var simple = _c[_b];
+ var match_1 = rangeRegExp.exec(simple);
+ if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
+ return undefined;
+ }
+ }
+ alternatives.push(comparators);
+ }
+ return alternatives;
+ }
+ function parsePartial(text) {
+ var match = partialRegExp.exec(text);
+ if (!match)
+ return undefined;
+ var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5];
+ var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build);
+ return { version: version, major: major, minor: minor, patch: patch };
+ }
+ function parseHyphen(left, right, comparators) {
+ var leftResult = parsePartial(left);
+ if (!leftResult)
+ return false;
+ var rightResult = parsePartial(right);
+ if (!rightResult)
+ return false;
+ if (!isWildcard(leftResult.major)) {
+ comparators.push(createComparator(">=", leftResult.version));
+ }
+ if (!isWildcard(rightResult.major)) {
+ comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
+ isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
+ createComparator("<=", rightResult.version));
+ }
+ return true;
+ }
+ function parseComparator(operator, text, comparators) {
+ var result = parsePartial(text);
+ if (!result)
+ return false;
+ var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
+ if (!isWildcard(major)) {
+ switch (operator) {
+ case "~":
+ comparators.push(createComparator(">=", version));
+ comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
+ "minor")));
+ break;
+ case "^":
+ comparators.push(createComparator(">=", version));
+ comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
+ version.minor > 0 || isWildcard(patch) ? "minor" :
+ "patch")));
+ break;
+ case "<":
+ case ">=":
+ comparators.push(createComparator(operator, version));
+ break;
+ case "<=":
+ case ">":
+ comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
+ isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
+ createComparator(operator, version));
+ break;
+ case "=":
+ case undefined:
+ if (isWildcard(minor) || isWildcard(patch)) {
+ comparators.push(createComparator(">=", version));
+ comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
+ }
+ else {
+ comparators.push(createComparator("=", version));
+ }
+ break;
+ default:
+ // unrecognized
+ return false;
+ }
+ }
+ else if (operator === "<" || operator === ">") {
+ comparators.push(createComparator("<", Version.zero));
+ }
+ return true;
+ }
+ function isWildcard(part) {
+ return part === "*" || part === "x" || part === "X";
+ }
+ function createComparator(operator, operand) {
+ return { operator: operator, operand: operand };
+ }
+ function testDisjunction(version, alternatives) {
+ // an empty disjunction is treated as "*" (all versions)
+ if (alternatives.length === 0)
+ return true;
+ for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
+ var alternative = alternatives_1[_i];
+ if (testAlternative(version, alternative))
+ return true;
+ }
+ return false;
+ }
+ function testAlternative(version, comparators) {
+ for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
+ var comparator = comparators_1[_i];
+ if (!testComparator(version, comparator.operator, comparator.operand))
+ return false;
+ }
+ return true;
+ }
+ function testComparator(version, operator, operand) {
+ var cmp = version.compareTo(operand);
+ switch (operator) {
+ case "<": return cmp < 0;
+ case "<=": return cmp <= 0;
+ case ">": return cmp > 0;
+ case ">=": return cmp >= 0;
+ case "=": return cmp === 0;
+ default: return ts.Debug.assertNever(operator);
+ }
+ }
+ function formatDisjunction(alternatives) {
+ return ts.map(alternatives, formatAlternative).join(" || ") || "*";
+ }
+ function formatAlternative(comparators) {
+ return ts.map(comparators, formatComparator).join(" ");
+ }
+ function formatComparator(comparator) {
+ return "" + comparator.operator + comparator.operand;
+ }
+})(ts || (ts = {}));
var ts;
(function (ts) {
// token > SyntaxKind.Identifier => token is a keyword
@@ -2753,32 +3120,32 @@ var ts;
SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
- SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value";
- SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type";
+ SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value";
+ SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type";
SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
// Variables can be redeclared, but can not redeclare a block-scoped declaration with the
// same name, or any other value that is not a variable, e.g. ValueModule or Class
- SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes";
+ SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes";
// Block-scoped declarations are not allowed to be re-declared
// they can not merge with anything in the value space
- SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes";
- SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes";
+ SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes";
+ SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes";
SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes";
- SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes";
+ SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes";
SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes";
- SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes";
+ SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes";
SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes";
SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes";
- SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes";
+ SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
- SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes";
- SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes";
- SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes";
- SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes";
- SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes";
+ SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes";
+ SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes";
+ SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes";
+ SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes";
+ SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes";
SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
@@ -3006,9 +3373,8 @@ var ts;
var InferenceFlags;
(function (InferenceFlags) {
InferenceFlags[InferenceFlags["None"] = 0] = "None";
- InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes";
- InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault";
- InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault";
+ InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
+ InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -4755,7 +5121,7 @@ var ts;
Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."),
Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."),
_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."),
- A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."),
+ A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."),
A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."),
A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."),
A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."),
@@ -4794,6 +5160,10 @@ var ts;
The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."),
A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"),
+ This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."),
+ use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."),
+ Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
+ use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."),
Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."),
@@ -5037,7 +5407,6 @@ var ts;
The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."),
Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
- Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."),
Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"),
Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"),
Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."),
@@ -5156,6 +5525,7 @@ var ts;
An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."),
Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."),
Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"),
+ Index_0_is_out_of_bounds_in_tuple_of_length_1: diag(2733, ts.DiagnosticCategory.Error, "Index_0_is_out_of_bounds_in_tuple_of_length_1_2733", "Index '{0}' is out-of-bounds in tuple of length {1}."),
Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
@@ -5269,7 +5639,8 @@ var ts;
Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
- Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."),
+ Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."),
+ Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
@@ -5363,7 +5734,7 @@ var ts;
Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."),
Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."),
- Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."),
+ Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."),
baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."),
rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."),
Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."),
@@ -5461,6 +5832,12 @@ var ts;
_0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
+ package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."),
+ package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."),
+ package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."),
+ package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."),
+ An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."),
+ An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."),
Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
@@ -6407,6 +6784,7 @@ var ts;
var token;
var tokenValue;
var tokenFlags;
+ var inJSDocType = 0;
setText(text, start, length);
return {
getStartPos: function () { return startPos; },
@@ -6436,6 +6814,7 @@ var ts;
setLanguageVariant: setLanguageVariant,
setOnError: setOnError,
setTextPos: setTextPos,
+ setInJSDocType: setInJSDocType,
tryScan: tryScan,
lookAhead: lookAhead,
scanRange: scanRange,
@@ -6891,6 +7270,7 @@ var ts;
function scan() {
startPos = pos;
tokenFlags = 0;
+ var asteriskSeen = false;
while (true) {
tokenPos = pos;
if (pos >= end) {
@@ -6929,6 +7309,24 @@ var ts;
case 11 /* verticalTab */:
case 12 /* formFeed */:
case 32 /* space */:
+ case 160 /* nonBreakingSpace */:
+ case 5760 /* ogham */:
+ case 8192 /* enQuad */:
+ case 8193 /* emQuad */:
+ case 8194 /* enSpace */:
+ case 8195 /* emSpace */:
+ case 8196 /* threePerEmSpace */:
+ case 8197 /* fourPerEmSpace */:
+ case 8198 /* sixPerEmSpace */:
+ case 8199 /* figureSpace */:
+ case 8200 /* punctuationSpace */:
+ case 8201 /* thinSpace */:
+ case 8202 /* hairSpace */:
+ case 8203 /* zeroWidthSpace */:
+ case 8239 /* narrowNoBreakSpace */:
+ case 8287 /* mathematicalSpace */:
+ case 12288 /* ideographicSpace */:
+ case 65279 /* byteOrderMark */:
if (skipTrivia) {
pos++;
continue;
@@ -6986,6 +7384,11 @@ var ts;
return pos += 2, token = 40 /* AsteriskAsteriskToken */;
}
pos++;
+ if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
+ // decoration at the start of a JSDoc comment line
+ asteriskSeen = true;
+ continue;
+ }
return token = 39 /* AsteriskToken */;
case 43 /* plus */:
if (text.charCodeAt(pos + 1) === 43 /* plus */) {
@@ -7568,6 +7971,9 @@ var ts;
tokenValue = undefined;
tokenFlags = 0;
}
+ function setInJSDocType(inType) {
+ inJSDocType += inType ? 1 : -1;
+ }
}
ts.createScanner = createScanner;
})(ts || (ts = {}));
@@ -7588,7 +7994,6 @@ var ts;
})(ts || (ts = {}));
/* @internal */
(function (ts) {
- ts.emptyArray = [];
ts.resolvingEmptyArray = [];
ts.emptyMap = ts.createMap();
ts.emptyUnderscoreEscapedMap = ts.emptyMap;
@@ -8014,12 +8419,20 @@ var ts;
return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
+ function isJSDocTypeExpressionOrChild(node) {
+ return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ }
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
if (nodeIsMissing(node)) {
return "";
}
- return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
+ var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
+ if (isJSDocTypeExpressionOrChild(node)) {
+ // strip space + asterisk at line start
+ text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
+ }
+ return text;
}
ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
function getTextOfNode(node, includeTrivia) {
@@ -8421,6 +8834,10 @@ var ts;
return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
}
ts.isEnumConst = isEnumConst;
+ function isDeclarationReadonly(declaration) {
+ return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration));
+ }
+ ts.isDeclarationReadonly = isDeclarationReadonly;
function isVarConst(node) {
return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
}
@@ -9235,6 +9652,10 @@ var ts;
return decl;
}
ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer;
+ function isAssignmentDeclaration(decl) {
+ return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl);
+ }
+ ts.isAssignmentDeclaration = isAssignmentDeclaration;
/** Get the initializer, taking into account defaulted Javascript initializers */
function getEffectiveInitializer(node) {
if (isInJavaScriptFile(node) && node.initializer &&
@@ -9572,6 +9993,10 @@ var ts;
result = ts.addRange(result, ts.getJSDocParameterTags(node));
break;
}
+ if (node.kind === 148 /* TypeParameter */) {
+ result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
+ break;
+ }
node = getNextJSDocCommentLocation(node);
}
return result || ts.emptyArray;
@@ -9762,6 +10187,12 @@ var ts;
return node;
}
ts.skipParentheses = skipParentheses;
+ function skipParenthesesUp(node) {
+ while (node.kind === 193 /* ParenthesizedExpression */) {
+ node = node.parent;
+ }
+ return node;
+ }
// a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
function isDeleteTarget(node) {
if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) {
@@ -9786,32 +10217,36 @@ var ts;
}
ts.isDeclarationName = isDeclarationName;
// See GH#16030
- function isAnyDeclarationName(name) {
+ function getDeclarationFromName(name) {
+ var parent = name.parent;
switch (name.kind) {
- case 71 /* Identifier */:
case 9 /* StringLiteral */:
- case 8 /* NumericLiteral */: {
- var parent = name.parent;
+ case 8 /* NumericLiteral */:
+ if (ts.isComputedPropertyName(parent))
+ return parent.parent;
+ // falls through
+ case 71 /* Identifier */:
if (ts.isDeclaration(parent)) {
- return parent.name === name;
+ return parent.name === name ? parent : undefined;
}
- else if (ts.isQualifiedName(name.parent)) {
- var tag = name.parent.parent;
- return ts.isJSDocParameterTag(tag) && tag.name === name.parent;
+ else if (ts.isQualifiedName(parent)) {
+ var tag = parent.parent;
+ return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
}
else {
- var binExp = name.parent.parent;
+ var binExp = parent.parent;
return ts.isBinaryExpression(binExp) &&
getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ &&
(binExp.left.symbol || binExp.symbol) &&
- ts.getNameOfDeclaration(binExp) === name;
+ ts.getNameOfDeclaration(binExp) === name
+ ? binExp
+ : undefined;
}
- }
default:
- return false;
+ return undefined;
}
}
- ts.isAnyDeclarationName = isAnyDeclarationName;
+ ts.getDeclarationFromName = getDeclarationFromName;
function isLiteralComputedPropertyDeclarationName(node) {
return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) &&
node.parent.kind === 147 /* ComputedPropertyName */ &&
@@ -11262,6 +11697,28 @@ var ts;
return getStringFromExpandedCharCodes(expandedCharCodes);
}
ts.base64decode = base64decode;
+ function readJson(path, host) {
+ try {
+ var jsonText = host.readFile(path);
+ if (!jsonText)
+ return {};
+ var result = ts.parseConfigFileTextToJson(path, jsonText);
+ if (result.error) {
+ return {};
+ }
+ return result.config;
+ }
+ catch (e) {
+ // gracefully handle if readFile fails or returns not JSON
+ return {};
+ }
+ }
+ ts.readJson = readJson;
+ function directoryProbablyExists(directoryName, host) {
+ // if host does not support 'directoryExists' assume that directory will exist
+ return !host.directoryExists || host.directoryExists(directoryName);
+ }
+ ts.directoryProbablyExists = directoryProbablyExists;
var carriageReturnLineFeed = "\r\n";
var lineFeed = "\n";
function getNewLineCharacter(options, getNewLine) {
@@ -11352,6 +11809,8 @@ var ts;
* @param end The end position.
*/
function createRange(pos, end) {
+ if (end === void 0) { end = pos; }
+ ts.Debug.assert(end >= pos || end === -1);
return { pos: pos, end: end };
}
ts.createRange = createRange;
@@ -11527,6 +11986,8 @@ var ts;
if (!parent)
return 0 /* Read */;
switch (parent.kind) {
+ case 193 /* ParenthesizedExpression */:
+ return accessKind(parent);
case 201 /* PostfixUnaryExpression */:
case 200 /* PrefixUnaryExpression */:
var operator = parent.operator;
@@ -11538,12 +11999,34 @@ var ts;
: 0 /* Read */;
case 187 /* PropertyAccessExpression */:
return parent.name !== node ? 0 /* Read */ : accessKind(parent);
+ case 273 /* PropertyAssignment */: {
+ var parentAccess = accessKind(parent.parent);
+ // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
+ return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
+ }
+ case 274 /* ShorthandPropertyAssignment */:
+ // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
+ return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
+ case 185 /* ArrayLiteralExpression */:
+ return accessKind(parent);
default:
return 0 /* Read */;
}
function writeOrReadWrite() {
// If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
- return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
+ return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
+ }
+ }
+ function reverseAccessKind(a) {
+ switch (a) {
+ case 0 /* Read */:
+ return 1 /* Write */;
+ case 1 /* Write */:
+ return 0 /* Read */;
+ case 2 /* ReadWrite */:
+ return 2 /* ReadWrite */;
+ default:
+ return ts.Debug.assertNever(a);
}
}
function compareDataObjects(dst, src) {
@@ -11769,13 +12252,6 @@ var ts;
return { start: start, length: length };
}
ts.createTextSpan = createTextSpan;
- /* @internal */
- function createTextRange(pos, end) {
- if (end === void 0) { end = pos; }
- ts.Debug.assert(end >= pos);
- return { pos: pos, end: end };
- }
- ts.createTextRange = createTextRange;
function createTextSpanFromBounds(start, end) {
return createTextSpan(start, end - start);
}
@@ -12103,13 +12579,13 @@ var ts;
if (ts.isDeclaration(hostNode)) {
return getDeclarationIdentifier(hostNode);
}
- // Covers remaining cases
+ // Covers remaining cases (returning undefined if none match).
switch (hostNode.kind) {
case 217 /* VariableStatement */:
if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
}
- return undefined;
+ break;
case 219 /* ExpressionStatement */:
var expr = hostNode.expression;
switch (expr.kind) {
@@ -12121,9 +12597,7 @@ var ts;
return arg;
}
}
- return undefined;
- case 1 /* EndOfFileToken */:
- return undefined;
+ break;
case 193 /* ParenthesizedExpression */: {
return getDeclarationIdentifier(hostNode.expression);
}
@@ -12131,10 +12605,8 @@ var ts;
if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) {
return getDeclarationIdentifier(hostNode.statement);
}
- return undefined;
+ break;
}
- default:
- ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!");
}
}
function getDeclarationIdentifier(node) {
@@ -12211,15 +12683,14 @@ var ts;
/**
* Gets the JSDoc parameter tags for the node if present.
*
- * @remarks Returns any JSDoc param tag that matches the provided
+ * @remarks Returns any JSDoc param tag whose name matches the provided
* parameter, whether a param tag on a containing function
* expression, or a param tag on a variable declaration whose
* initializer is the containing function. The tags closest to the
* node are returned first, so in the previous example, the param
* tag on the containing function expression would be first.
*
- * Does not return tags for binding patterns, because JSDoc matches
- * parameters by name and binding patterns do not have a name.
+ * For binding patterns, parameter tags are matched by position.
*/
function getJSDocParameterTags(param) {
if (param.name) {
@@ -12240,6 +12711,23 @@ var ts;
return ts.emptyArray;
}
ts.getJSDocParameterTags = getJSDocParameterTags;
+ /**
+ * Gets the JSDoc type parameter tags for the node if present.
+ *
+ * @remarks Returns any JSDoc template tag whose names match the provided
+ * parameter, whether a template tag on a containing function
+ * expression, or a template tag on a variable declaration whose
+ * initializer is the containing function. The tags closest to the
+ * node are returned first, so in the previous example, the template
+ * tag on the containing function expression would be first.
+ */
+ function getJSDocTypeParameterTags(param) {
+ var name = param.name.escapedText;
+ return getJSDocTags(param.parent).filter(function (tag) {
+ return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
+ });
+ }
+ ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
/**
* Return true if the node has JSDoc parameter tags.
*
@@ -12366,7 +12854,20 @@ var ts;
ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
- return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray);
+ if (node.typeParameters) {
+ return node.typeParameters;
+ }
+ if (ts.isInJavaScriptFile(node)) {
+ var decls = ts.getJSDocTypeParameterDeclarations(node);
+ if (decls.length) {
+ return decls;
+ }
+ var typeTag = getJSDocType(node);
+ if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
+ return typeTag.typeParameters;
+ }
+ }
+ return ts.emptyArray;
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getEffectiveConstraintOfTypeParameter(node) {
@@ -14105,6 +14606,18 @@ var ts;
return moduleResolution;
}
ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
+ function hasJsonModuleEmitEnabled(options) {
+ switch (getEmitModuleKind(options)) {
+ case ts.ModuleKind.CommonJS:
+ case ts.ModuleKind.AMD:
+ case ts.ModuleKind.ES2015:
+ case ts.ModuleKind.ESNext:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
function unreachableCodeIsError(options) {
return options.allowUnreachableCode === false;
}
@@ -14414,8 +14927,6 @@ var ts;
if (pathComponents.length === 0)
return "";
var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]);
- if (pathComponents.length === 1)
- return root;
return root + pathComponents.slice(1).join(ts.directorySeparator);
}
ts.getPathFromPathComponents = getPathFromPathComponents;
@@ -14927,6 +15438,7 @@ var ts;
/** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
+ ts.supportedJavaScriptAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions);
function getSupportedExtensions(options, extraFileExtensions) {
var needJsExtensions = options && options.allowJs;
@@ -14944,6 +15456,10 @@ var ts;
return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
}
ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension;
+ function hasJavaScriptOrJsonFileExtension(fileName) {
+ return ts.supportedJavaScriptAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); });
+ }
+ ts.hasJavaScriptOrJsonFileExtension = hasJavaScriptOrJsonFileExtension;
function hasTypeScriptFileExtension(fileName) {
return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
}
@@ -15346,6 +15862,7 @@ var ts;
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.questionToken) ||
+ visitNode(cbNode, node.exclamationToken) ||
visitNode(cbNode, node.equalsToken) ||
visitNode(cbNode, node.objectAssignmentInitializer);
case 275 /* SpreadAssignment */:
@@ -15416,6 +15933,7 @@ var ts;
visitNode(cbNode, node.asteriskToken) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.questionToken) ||
+ visitNode(cbNode, node.exclamationToken) ||
visitNodes(cbNode, cbNodes, node.typeParameters) ||
visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type) ||
@@ -15774,7 +16292,7 @@ var ts;
ts.performance.mark("beforeParse");
var result;
if (languageVersion === 100 /* JSON */) {
- result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes);
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
}
else {
result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
@@ -15943,8 +16461,12 @@ var ts;
if (scriptKind === 6 /* JSON */) {
var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ result_1.referencedFiles = ts.emptyArray;
result_1.typeReferenceDirectives = ts.emptyArray;
+ result_1.libReferenceDirectives = ts.emptyArray;
result_1.amdDependencies = ts.emptyArray;
+ result_1.hasNoDefaultLib = false;
+ result_1.pragmas = ts.emptyMap;
return result_1;
}
initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
@@ -17380,8 +17902,10 @@ var ts;
return finishNode(parameter);
}
function parseJSDocType() {
+ scanner.setInJSDocType(true);
var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */);
var type = parseTypeOrTypePredicate();
+ scanner.setInJSDocType(false);
if (dotdotdot) {
var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
@@ -19477,8 +20001,9 @@ var ts;
var asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
var tokenIsIdentifier = isIdentifier();
node.name = parsePropertyName();
- // Disallowing of optional property assignments happens in the grammar checker.
+ // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
node.questionToken = parseOptionalToken(55 /* QuestionToken */);
+ node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */);
if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
return parseMethodDeclaration(node, asteriskToken);
}
@@ -21389,7 +21914,7 @@ var ts;
}
function parseTypedefTag(atToken, tagName, indent) {
var typeExpression = tryParseTypeExpression();
- skipWhitespace();
+ skipWhitespaceOrAsterisk();
var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
@@ -22411,9 +22936,7 @@ var ts;
*/
/* @internal */
ts.libMap = ts.createMapFromEntries(libEntries);
- /* @internal */
- ts.optionDeclarations = [
- // CommandLine only options
+ var commonOptionsWithBuild = [
{
name: "help",
shortName: "h",
@@ -22427,6 +22950,24 @@ var ts;
shortName: "?",
type: "boolean"
},
+ {
+ name: "preserveWatchOutput",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
+ },
+ {
+ name: "watch",
+ shortName: "w",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Watch_input_files,
+ },
+ ];
+ /* @internal */
+ ts.optionDeclarations = commonOptionsWithBuild.concat([
{
name: "all",
type: "boolean",
@@ -22474,21 +23015,6 @@ var ts;
category: ts.Diagnostics.Command_line_Options,
description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
},
- {
- name: "preserveWatchOutput",
- type: "boolean",
- showInSimplifiedHelpView: false,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
- },
- {
- name: "watch",
- shortName: "w",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Watch_input_files,
- },
// Basic
{
name: "target",
@@ -23093,7 +23619,37 @@ var ts;
},
description: ts.Diagnostics.List_of_language_service_plugins
}
- ];
+ ]);
+ /* @internal */
+ ts.buildOpts = commonOptionsWithBuild.concat([
+ {
+ name: "verbose",
+ shortName: "v",
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Enable_verbose_logging,
+ type: "boolean"
+ },
+ {
+ name: "dry",
+ shortName: "d",
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
+ type: "boolean"
+ },
+ {
+ name: "force",
+ shortName: "f",
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
+ type: "boolean"
+ },
+ {
+ name: "clean",
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
+ type: "boolean"
+ }
+ ]);
/* @internal */
ts.typeAcquisitionDeclarations = [
{
@@ -23146,20 +23702,21 @@ var ts;
}
ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
function getOptionNameMap() {
- if (optionNameMapCache) {
- return optionNameMapCache;
- }
+ return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations));
+ }
+ /*@internal*/
+ function createOptionNameMap(optionDeclarations) {
var optionNameMap = ts.createMap();
var shortOptionNames = ts.createMap();
- ts.forEach(ts.optionDeclarations, function (option) {
+ ts.forEach(optionDeclarations, function (option) {
optionNameMap.set(option.name.toLowerCase(), option);
if (option.shortName) {
shortOptionNames.set(option.shortName, option.name);
}
});
- optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames };
- return optionNameMapCache;
+ return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames };
}
+ ts.createOptionNameMap = createOptionNameMap;
/* @internal */
function createCompilerDiagnosticForInvalidCustomType(opt) {
return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
@@ -23306,6 +23863,11 @@ var ts;
ts.parseCommandLine = parseCommandLine;
/** @internal */
function getOptionFromName(optionName, allowShort) {
+ return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort);
+ }
+ ts.getOptionFromName = getOptionFromName;
+ /*@internal*/
+ function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
if (allowShort === void 0) { allowShort = false; }
optionName = optionName.toLowerCase();
var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames;
@@ -23318,7 +23880,50 @@ var ts;
}
return optionNameMap.get(optionName);
}
- ts.getOptionFromName = getOptionFromName;
+ ts.getOptionDeclarationFromName = getOptionDeclarationFromName;
+ /*@internal*/
+ function parseBuildCommand(args) {
+ var buildOptionNameMap;
+ var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); };
+ var buildOptions = {};
+ var projects = [];
+ var errors;
+ for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
+ var arg = args_4[_i];
+ if (arg.charCodeAt(0) === 45 /* minus */) {
+ var opt = getOptionDeclarationFromName(returnBuildOptionNameMap, arg.slice(arg.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true);
+ if (opt) {
+ buildOptions[opt.name] = true;
+ }
+ else {
+ (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_build_option_0, arg));
+ }
+ }
+ else {
+ // Not a flag, parse as filename
+ projects.push(arg);
+ }
+ }
+ if (projects.length === 0) {
+ // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
+ projects.push(".");
+ }
+ // Nonsensical combinations
+ if (buildOptions.clean && buildOptions.force) {
+ (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
+ }
+ if (buildOptions.clean && buildOptions.verbose) {
+ (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
+ }
+ if (buildOptions.clean && buildOptions.watch) {
+ (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
+ }
+ if (buildOptions.watch && buildOptions.dry) {
+ (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
+ }
+ return { buildOptions: buildOptions, projects: projects, errors: errors || ts.emptyArray };
+ }
+ ts.parseBuildCommand = parseBuildCommand;
function getDiagnosticText(_message) {
var _args = [];
for (var _i = 1; _i < arguments.length; _i++) {
@@ -24653,6 +25258,12 @@ var ts;
function noPackageId(r) {
return withPackageId(/*packageId*/ undefined, r);
}
+ function removeIgnoredPackageId(r) {
+ if (r) {
+ ts.Debug.assert(r.packageId === undefined);
+ return { path: r.path, ext: r.extension };
+ }
+ }
/**
* Kinds of file that we are currently looking for.
* Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
@@ -24678,48 +25289,94 @@ var ts;
failedLookupLocations: failedLookupLocations
};
}
- /** Reads from "main" or "types"/"typings" depending on `extensions`. */
- function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) {
- return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main");
- function tryReadFromField(fieldName) {
- if (!ts.hasProperty(jsonContent, fieldName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
- }
- return;
- }
- var fileName = jsonContent[fieldName];
- if (!ts.isString(fileName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName);
- }
- return;
- }
- var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
+ function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
+ if (!ts.hasProperty(jsonContent, fieldName)) {
if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
}
- return path;
+ return;
}
+ var value = jsonContent[fieldName];
+ if (typeof value !== typeOfTag || value === null) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
+ }
+ return;
+ }
+ return value;
}
+ function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
+ var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
+ if (fileName === undefined)
+ return;
+ var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
+ }
+ return path;
+ }
+ function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
+ return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
+ || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
+ }
+ function readPackageJsonMainField(jsonContent, baseDirectory, state) {
+ return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
+ }
+ function readPackageJsonTypesVersionsField(jsonContent, state) {
+ var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
+ if (typesVersions === undefined)
+ return;
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
+ }
+ return typesVersions;
+ }
+ function readPackageJsonTypesVersionPaths(jsonContent, state) {
+ var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
+ if (typesVersions === undefined)
+ return;
+ if (state.traceEnabled) {
+ for (var key in typesVersions) {
+ if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
+ trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
+ }
+ }
+ }
+ var result = getPackageJsonTypesVersionsPaths(typesVersions);
+ if (!result) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
+ }
+ return;
+ }
+ var bestVersionKey = result.version, bestVersionPaths = result.paths;
+ if (typeof bestVersionPaths !== "object") {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
+ }
+ return;
+ }
+ return result;
+ }
+ var typeScriptVersion;
/* @internal */
- function readJson(path, host) {
- try {
- var jsonText = host.readFile(path);
- if (!jsonText)
- return {};
- var result = ts.parseConfigFileTextToJson(path, jsonText);
- if (result.error) {
- return {};
+ function getPackageJsonTypesVersionsPaths(typesVersions) {
+ if (!typeScriptVersion)
+ typeScriptVersion = new ts.Version(ts.version);
+ for (var key in typesVersions) {
+ if (!ts.hasProperty(typesVersions, key))
+ continue;
+ var keyRange = ts.VersionRange.tryParse(key);
+ if (keyRange === undefined) {
+ continue;
+ }
+ // return the first entry whose range matches the current compiler version.
+ if (keyRange.test(typeScriptVersion)) {
+ return { version: key, paths: typesVersions[key] };
}
- return result.config;
- }
- catch (e) {
- // gracefully handle if readFile fails or returns not JSON
- return {};
}
}
- ts.readJson = readJson;
+ ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
function getEffectiveTypeRoots(options, host) {
if (options.typeRoots) {
return options.typeRoots;
@@ -24763,7 +25420,8 @@ var ts;
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
var traceEnabled = isTraceEnabled(options, host);
- var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled };
+ var failedLookupLocations = [];
+ var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
var typeRoots = getEffectiveTypeRoots(options, host);
if (traceEnabled) {
if (containingFile === undefined) {
@@ -24783,7 +25441,6 @@ var ts;
}
}
}
- var failedLookupLocations = [];
var resolved = primaryLookup();
var primary = true;
if (!resolved) {
@@ -24810,11 +25467,11 @@ var ts;
return ts.forEach(typeRoots, function (typeRoot) {
var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
var candidateDirectory = ts.getDirectoryPath(candidate);
- var directoryExists = directoryProbablyExists(candidateDirectory, host);
+ var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
if (!directoryExists && traceEnabled) {
trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
}
- return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState));
+ return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
});
}
else {
@@ -24830,7 +25487,7 @@ var ts;
if (traceEnabled) {
trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
}
- var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined);
+ var result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined);
var resolvedFile = resolvedTypeScriptOnly(result && result.value);
if (!resolvedFile && traceEnabled) {
trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
@@ -24869,11 +25526,11 @@ var ts;
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 packageJsonPath = ts.combinePaths(root, normalized, "package.json");
// `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
// See `createNotNeededPackageJSON` in the types-publisher` repo.
// tslint:disable-next-line:no-null-keyword
- var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
+ var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
if (!isNotNeededPackage) {
// Return just the type directive names
result.push(ts.getBaseFileName(normalized));
@@ -25099,15 +25756,15 @@ var ts;
* 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(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) {
+ function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
if (!ts.isExternalModuleNameRelative(moduleName)) {
- return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state);
+ return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
}
else {
- return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state);
+ return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
}
}
- function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) {
+ function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
if (!state.compilerOptions.rootDirs) {
return undefined;
}
@@ -25145,7 +25802,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
}
- var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
+ var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
@@ -25164,7 +25821,7 @@ var ts;
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(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
+ var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
if (resolvedFileName_1) {
return resolvedFileName_1;
}
@@ -25175,56 +25832,29 @@ var ts;
}
return undefined;
}
- function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) {
- if (!state.compilerOptions.baseUrl) {
+ function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
+ var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
+ if (!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);
+ trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
}
- // string is for exact match
- var matchedPattern;
- if (state.compilerOptions.paths) {
+ if (paths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
}
- matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
- }
- if (matchedPattern) {
- var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
- var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
+ var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
+ if (resolved) {
+ return resolved.value;
}
- return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) {
- var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : 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);
- }
- // A path mapping may have an extension, in contrast to an import, which should omit it.
- var extension = ts.tryGetExtensionFromPath(candidate);
- if (extension !== undefined) {
- var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state);
- if (path_1 !== undefined) {
- return noPackageId({ path: path_1, ext: extension });
- }
- }
- return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
- });
}
- 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(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
}
+ return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
}
- function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) {
- return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false);
- }
- ts.nodeModuleNameResolver = nodeModuleNameResolver;
/**
* Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
* No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
@@ -25239,10 +25869,14 @@ var ts;
return resolvedModule.resolvedFileName;
}
ts.resolveJavaScriptModule = resolveJavaScriptModule;
+ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) {
+ return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false);
+ }
+ ts.nodeModuleNameResolver = nodeModuleNameResolver;
function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
var failedLookupLocations = [];
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
var result = jsOnly ?
tryResolve(Extensions.JavaScript) :
(tryResolve(Extensions.TypeScript) ||
@@ -25254,8 +25888,8 @@ var ts;
}
return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
function tryResolve(extensions) {
- var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); };
- var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state);
+ var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
+ var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
if (resolved) {
return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) });
}
@@ -25263,7 +25897,7 @@ var ts;
if (traceEnabled) {
trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
}
- var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache);
+ var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache);
if (!resolved_1)
return undefined;
var resolvedValue = resolved_1.value;
@@ -25277,7 +25911,7 @@ var ts;
}
else {
var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
- var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
+ var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
// Treat explicit "node_modules" import as an external library import.
return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
}
@@ -25294,29 +25928,30 @@ var ts;
ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line
return real;
}
- function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) {
+ function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
}
if (!ts.hasTrailingDirectorySeparator(candidate)) {
if (!onlyRecordFailures) {
var parentOfCandidate = ts.getDirectoryPath(candidate);
- if (!directoryProbablyExists(parentOfCandidate, state.host)) {
+ if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
}
onlyRecordFailures = true;
}
}
- var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state);
+ var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
if (resolvedFromFile) {
var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
- var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId;
+ var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state);
+ var packageId = packageInfo && packageInfo.packageId;
return withPackageId(packageId, resolvedFromFile);
}
}
if (!onlyRecordFailures) {
- var candidateExists = directoryProbablyExists(candidate, state.host);
+ var candidateExists = ts.directoryProbablyExists(candidate, state.host);
if (!candidateExists) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
@@ -25324,7 +25959,7 @@ var ts;
onlyRecordFailures = true;
}
}
- return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson);
+ return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
}
/*@internal*/
ts.nodeModulesPathPart = "/node_modules/";
@@ -25365,31 +26000,25 @@ var ts;
if (ts.endsWith(path, ".d.ts")) {
return path;
}
- if (ts.endsWith(path, "/index")) {
+ if (path === "index" || ts.endsWith(path, "/index")) {
return path + ".d.ts";
}
return path + "/index.d.ts";
}
- /* @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;
- function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
- return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state));
+ function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
+ return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
}
/**
* @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(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
+ function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
if (extensions === Extensions.Json) {
var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
- return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
+ return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, 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, failedLookupLocations, onlyRecordFailures, state);
+ var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
if (resolvedByAddingExtension) {
return resolvedByAddingExtension;
}
@@ -25401,16 +26030,16 @@ var ts;
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, failedLookupLocations, onlyRecordFailures, state);
+ return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
}
}
/** Try to return an existing file that adds one of the `extensions` to `candidate`. */
- function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) {
+ function tryAddingExtensions(candidate, extensions, 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);
+ onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
}
}
switch (extensions) {
@@ -25424,12 +26053,12 @@ var ts;
return tryExtension(".json" /* Json */);
}
function tryExtension(ext) {
- var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state);
+ var path = tryFile(candidate + ext, onlyRecordFailures, state);
return path === undefined ? undefined : { path: path, ext: ext };
}
}
/** Return the file if it exists. */
- function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) {
+ function tryFile(fileName, onlyRecordFailures, state) {
if (!onlyRecordFailures) {
if (state.host.fileExists(fileName)) {
if (state.traceEnabled) {
@@ -25443,39 +26072,40 @@ var ts;
}
}
}
- failedLookupLocations.push(fileName);
+ state.failedLookupLocations.push(fileName);
return undefined;
}
- function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) {
+ function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
if (considerPackageJson === void 0) { considerPackageJson = true; }
- var _a = considerPackageJson
- ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state)
- : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId;
- return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent));
+ var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined;
+ var packageId = packageInfo && packageInfo.packageId;
+ var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
+ var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state);
+ return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
- function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) {
- var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state);
+ function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths) {
+ var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state);
if (fromPackageJson) {
return fromPackageJson;
}
- var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
- return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state);
+ var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(candidate, state.host);
+ return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), !directoryExists, state);
}
- function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) {
+ function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) {
var host = state.host, traceEnabled = state.traceEnabled;
- var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host);
- var packageJsonPath = pathToPackageJson(nodeModuleDirectory);
+ var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
+ var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
if (directoryExists && host.fileExists(packageJsonPath)) {
- var packageJsonContent = readJson(packageJsonPath, host);
+ var packageJsonContent = ts.readJson(packageJsonPath, host);
if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName
- var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state);
+ var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state);
if (typeof path === "string") {
- subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1));
+ subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1));
}
else {
- var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state);
- if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) {
- var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1);
+ var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state);
+ if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) {
+ var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1);
subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) {
return ts.tryRemoveExtension(potentialSubModule_1, extension);
}) || potentialSubModule_1) + ".d.ts" /* Dts */;
@@ -25488,6 +26118,7 @@ var ts;
if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) {
subModuleName = addExtensionAndIndex(subModuleName);
}
+ var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string"
? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version }
: undefined;
@@ -25499,23 +26130,24 @@ var ts;
trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
}
}
- return { found: true, packageJsonContent: packageJsonContent, packageId: packageId };
+ return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths };
}
else {
if (directoryExists && traceEnabled) {
trace(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
- failedLookupLocations.push(packageJsonPath);
- return { found: false, packageJsonContent: undefined, packageId: undefined };
+ state.failedLookupLocations.push(packageJsonPath);
}
}
- function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) {
- var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
+ function loadModuleFromPackageJson(jsonContent, versionPaths, extensions, candidate, state) {
+ var file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json
+ ? readPackageJsonTypesFields(jsonContent, candidate, state)
+ : readPackageJsonMainField(jsonContent, candidate, state);
if (!file) {
if (extensions === Extensions.TypeScript) {
// When resolving typescript modules, try resolving using main field as well
- file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state);
+ file = readPackageJsonMainField(jsonContent, candidate, state);
if (!file) {
return undefined;
}
@@ -25524,26 +26156,35 @@ var ts;
return undefined;
}
}
- var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host);
- var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state);
- if (fromFile) {
- var resolved = resolvedIfExtensionMatches(extensions, fromFile);
- if (resolved) {
- return resolved;
+ var loader = function (extensions, candidate, onlyRecordFailures, state) {
+ var fromFile = tryFile(candidate, onlyRecordFailures, state);
+ if (fromFile) {
+ var resolved = resolvedIfExtensionMatches(extensions, fromFile);
+ if (resolved) {
+ return noPackageId(resolved);
+ }
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
+ }
}
+ // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
+ var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
+ // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
+ return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
+ };
+ var onlyRecordFailures = !ts.directoryProbablyExists(ts.getDirectoryPath(file), state.host);
+ if (versionPaths && ts.containsPath(candidate, file)) {
+ var moduleName = ts.getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false);
if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
+ trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName);
+ }
+ var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state);
+ if (result) {
+ return removeIgnoredPackageId(result.value);
}
}
- // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
- var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
- // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
- var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false);
- if (result) {
- // It won't have a `packageId` set, because we disabled `considerPackageJson`.
- ts.Debug.assert(result.packageId === undefined);
- return { path: result.path, ext: result.extension };
- }
+ // It won't have a `packageId` set, because we disabled `considerPackageJson`.
+ return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state));
}
/** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
function resolvedIfExtensionMatches(extensions, path) {
@@ -25563,87 +26204,129 @@ var ts;
return extension === ".d.ts" /* Dts */;
}
}
- function pathToPackageJson(directory) {
- return ts.combinePaths(directory, "package.json");
- }
- function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) {
- var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
- // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
- var packageJsonContent;
- var packageId;
- var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state);
- if (packageInfo.found) {
- (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId);
- }
- else {
- var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
- if (rest !== "") { // If "rest" is empty, we just did this search above.
- var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName);
- // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId.
- packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId;
- }
- }
- var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) ||
- loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent);
- return withPackageId(packageId, pathAndExtension);
- }
/* @internal */
- function getPackageName(moduleName) {
+ function parsePackageName(moduleName) {
var idx = moduleName.indexOf(ts.directorySeparator);
if (moduleName[0] === "@") {
idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
}
return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
}
- ts.getPackageName = getPackageName;
- function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) {
- return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache);
+ ts.parsePackageName = parsePackageName;
+ function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) {
+ return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache);
}
- function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) {
+ function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
// Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
- return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined);
+ return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined);
}
- function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) {
+ function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) {
var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName);
return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
- var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations);
+ var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
if (resolutionFromCache) {
return resolutionFromCache;
}
- return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly));
+ return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
}
});
}
- /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */
- function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) {
- if (typesOnly === void 0) { typesOnly = false; }
+ function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
- var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
+ var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
if (!nodeModulesFolderExists && state.traceEnabled) {
trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
}
- var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state);
+ var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
if (packageResult) {
return packageResult;
}
if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) {
var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
var nodeModulesAtTypesExists = nodeModulesFolderExists;
- if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
+ if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
}
nodeModulesAtTypesExists = false;
}
- return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state);
+ return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
+ }
+ }
+ function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
+ var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
+ // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
+ var packageJsonContent;
+ var packageId;
+ var versionPaths;
+ var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state);
+ if (packageInfo) {
+ (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths);
+ var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
+ if (fromFile) {
+ return noPackageId(fromFile);
+ }
+ var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths);
+ return withPackageId(packageId, fromDirectory);
+ }
+ var loader = function (extensions, candidate, onlyRecordFailures, state) {
+ var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
+ loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths);
+ return withPackageId(packageId, pathAndExtension);
+ };
+ var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
+ if (rest !== "") { // If "rest" is empty, we just did this search above.
+ var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
+ // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
+ var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state);
+ if (packageInfo_1)
+ (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths);
+ if (versionPaths) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest);
+ }
+ var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
+ var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state);
+ if (fromPaths) {
+ return fromPaths.value;
+ }
+ }
+ }
+ return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
+ }
+ function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
+ var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
+ if (matchedPattern) {
+ var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
+ var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
+ }
+ var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
+ var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
+ var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
+ }
+ // A path mapping may have an extension, in contrast to an import, which should omit it.
+ var extension = ts.tryGetExtensionFromPath(candidate);
+ if (extension !== undefined) {
+ var path_1 = tryFile(candidate, onlyRecordFailures, state);
+ if (path_1 !== undefined) {
+ return noPackageId({ path: path_1, ext: extension });
+ }
+ }
+ return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
+ });
+ return { value: resolved };
}
}
/** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
var mangledScopedPackageSeparator = "__";
/** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
- function mangleScopedPackage(packageName, state) {
- var mangled = getMangledNameForScopedPackage(packageName);
+ function mangleScopedPackageNameWithTrace(packageName, state) {
+ var mangled = mangleScopedPackageName(packageName);
if (state.traceEnabled && mangled !== packageName) {
trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
}
@@ -25651,11 +26334,11 @@ var ts;
}
/* @internal */
function getTypesPackageName(packageName) {
- return "@types/" + getMangledNameForScopedPackage(packageName);
+ return "@types/" + mangleScopedPackageName(packageName);
}
ts.getTypesPackageName = getTypesPackageName;
/* @internal */
- function getMangledNameForScopedPackage(packageName) {
+ function mangleScopedPackageName(packageName) {
if (ts.startsWith(packageName, "@")) {
var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
if (replaceSlash !== packageName) {
@@ -25664,43 +26347,44 @@ var ts;
}
return packageName;
}
- ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage;
+ ts.mangleScopedPackageName = mangleScopedPackageName;
/* @internal */
- function getPackageNameFromAtTypesDirectory(mangledName) {
+ function getPackageNameFromTypesPackageName(mangledName) {
var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
if (withoutAtTypePrefix !== mangledName) {
- return getUnmangledNameForScopedPackage(withoutAtTypePrefix);
+ return unmangleScopedPackageName(withoutAtTypePrefix);
}
return mangledName;
}
- ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory;
+ ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
/* @internal */
- function getUnmangledNameForScopedPackage(typesPackageName) {
+ function unmangleScopedPackageName(typesPackageName) {
return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
"@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
typesPackageName;
}
- ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage;
- function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) {
+ ts.unmangleScopedPackageName = unmangleScopedPackageName;
+ function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
+ var _a;
var result = cache && cache.get(containingDirectory);
if (result) {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
- failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations);
+ (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations);
return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
}
}
function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
var failedLookupLocations = [];
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
var containingDirectory = ts.getDirectoryPath(containingFile);
var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
// No originalPath because classic resolution doesn't resolve realPath
return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations);
function tryResolve(extensions) {
- var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state);
+ var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
if (resolvedUsingSettings) {
return { value: resolvedUsingSettings };
}
@@ -25708,24 +26392,24 @@ var ts;
var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName);
// Climb up parent directories looking for a module.
var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
- var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations);
+ var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
if (resolutionFromCache) {
return resolutionFromCache;
}
var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
- return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state));
+ return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
});
if (resolved_3) {
return resolved_3;
}
if (extensions === Extensions.TypeScript) {
// If we didn't find the file normally, look it up in @types.
- return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state);
+ return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
}
}
else {
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state));
+ return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
}
}
}
@@ -25740,9 +26424,9 @@ var ts;
if (traceEnabled) {
trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
}
- var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
var failedLookupLocations = [];
- var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state);
+ var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
+ var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations);
}
ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
@@ -25957,11 +26641,12 @@ var ts;
if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
symbol.members = ts.createSymbolTable();
}
- if (symbolFlags & 67216319 /* Value */) {
+ if (symbolFlags & 67220415 /* Value */) {
var valueDeclaration = symbol.valueDeclaration;
if (!valueDeclaration ||
+ (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) ||
(valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) {
- // other kinds of value declarations take precedence over modules
+ // other kinds of value declarations take precedence over modules and assignment declarations
symbol.valueDeclaration = node;
}
}
@@ -26088,7 +26773,8 @@ var ts;
// prototype symbols like methods.
symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
}
- else {
+ else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* JSContainer */)) {
+ // JSContainers are allowed to merge with variables, no matter what other flags they have.
if (ts.isNamedDeclaration(node)) {
node.name.parent = node;
}
@@ -26171,7 +26857,7 @@ var ts;
if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) {
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
}
- var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0;
+ var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0;
var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
node.localSymbol = local;
@@ -26432,6 +27118,8 @@ var ts;
return isNarrowingBinaryExpression(expr);
case 200 /* PrefixUnaryExpression */:
return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
+ case 197 /* TypeOfExpression */:
+ return isNarrowingExpression(expr.expression);
}
return false;
}
@@ -27230,7 +27918,7 @@ var ts;
errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
}
}
- var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */);
+ var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
}
}
@@ -27250,7 +27938,7 @@ var ts;
function declareModuleSymbol(node) {
var state = getModuleInstanceState(node);
var instantiated = state !== 0 /* NonInstantiated */;
- declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
+ declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
return state;
}
function bindFunctionOrConstructorType(node) {
@@ -27338,9 +28026,6 @@ var ts;
declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
- function bindBlockScopedVariableDeclaration(node) {
- bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */);
- }
function delayedBindJSDocTypedefTag() {
if (!delayedTypeAliases) {
return;
@@ -27360,7 +28045,7 @@ var ts;
bind(typeAlias.typeExpression);
if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) {
parent = typeAlias.parent;
- bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
+ bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */);
}
else {
bind(typeAlias.fullName);
@@ -27632,7 +28317,7 @@ var ts;
while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
parentNode = parentNode.parent;
}
- bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
+ bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */);
break;
}
// falls through
@@ -27652,8 +28337,8 @@ var ts;
if (ts.isInJavaScriptFile(node) &&
file.commonJsModuleIndicator &&
ts.isModuleExportsPropertyAccessExpression(node) &&
- !lookupSymbolForNameWorker(container, "module")) {
- declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */);
+ !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
+ declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */);
}
break;
case 202 /* BinaryExpression */:
@@ -27730,15 +28415,15 @@ var ts;
// as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
// so that it will conflict with any other object literal members with the same
// name.
- return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */);
+ return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */);
case 237 /* FunctionDeclaration */:
return bindFunctionDeclaration(node);
case 155 /* Constructor */:
return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
case 156 /* GetAccessor */:
- return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */);
+ return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */);
case 157 /* SetAccessor */:
- return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */);
+ return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 163 /* FunctionType */:
case 287 /* JSDocFunctionType */:
case 291 /* JSDocSignature */:
@@ -27765,9 +28450,9 @@ var ts;
inStrictMode = true;
return bindClassLikeDeclaration(node);
case 239 /* InterfaceDeclaration */:
- return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */);
+ return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */);
case 240 /* TypeAliasDeclaration */:
- return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
+ return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */);
case 241 /* EnumDeclaration */:
return bindEnumDeclaration(node);
case 242 /* ModuleDeclaration */:
@@ -28048,14 +28733,13 @@ var ts;
}
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
- var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ &&
- !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left))
+ var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */
: propertyAccess.parent.parent.kind === 277 /* SourceFile */;
- if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) {
+ if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevel) {
// make symbols or add declarations for intermediate containers
var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */;
- var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */;
+ var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */;
namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) {
if (symbol) {
addDeclarationToSymbol(symbol, id, flags_1);
@@ -28073,12 +28757,10 @@ var ts;
var symbolTable = isPrototypeProperty ?
(namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
(namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
- // Declare the method/property
- var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0;
var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess));
- var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag;
- var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag;
- declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes);
+ var includes = isMethod ? 8192 /* Method */ : 4 /* Property */;
+ var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */;
+ declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* JSContainer */, excludes & ~67108864 /* JSContainer */);
}
/**
* Javascript containers are:
@@ -28187,8 +28869,11 @@ var ts;
checkStrictModeEvalOrArguments(node, node.name);
}
if (!ts.isBindingPattern(node.name)) {
+ var isEnum = !!ts.getJSDocEnumTag(node);
+ var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */);
+ var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */);
if (ts.isBlockOrCatchScoped(node)) {
- bindBlockScopedVariableDeclaration(node);
+ bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes);
}
else if (ts.isParameterDeclaration(node)) {
// It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
@@ -28200,10 +28885,10 @@ var ts;
// function foo([a,a]) {} // Duplicate Identifier error
// function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
// // which correctly set excluded symbols
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */);
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */);
}
else {
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */);
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes);
}
}
}
@@ -28220,7 +28905,7 @@ var ts;
bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
}
else {
- declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */);
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */);
}
// If this is a property-parameter, then also declare the property symbol into the
// containing class.
@@ -28238,10 +28923,10 @@ var ts;
checkStrictModeFunctionName(node);
if (inStrictMode) {
checkStrictModeFunctionDeclaration(node);
- bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */);
+ bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */);
}
else {
- declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */);
+ declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */);
}
}
function bindFunctionExpression(node) {
@@ -28279,10 +28964,10 @@ var ts;
if (!container_1.locals) {
container_1.locals = ts.createSymbolTable();
}
- declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
+ declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
}
else {
- declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
+ declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
}
}
else if (node.parent.kind === 174 /* InferType */) {
@@ -28291,14 +28976,14 @@ var ts;
if (!container_2.locals) {
container_2.locals = ts.createSymbolTable();
}
- declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
+ declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
}
else {
bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
}
}
else {
- declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
+ declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
}
}
// reachability checks
@@ -28317,9 +29002,7 @@ var ts;
// report error on class declarations
node.kind === 238 /* ClassDeclaration */ ||
// report error on instantiated modules or const-enums only modules if preserveConstEnums is set
- (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) ||
- // report error on regular enums and const enums if preserveConstEnums is set
- (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums));
+ (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
if (reportError) {
currentFlow = reportedUnreachableFlow;
if (!options.allowUnreachableCode) {
@@ -28357,7 +29040,7 @@ var ts;
// As opposed to a pure declaration like an `interface`
function isExecutableStatement(s) {
// Don't remove statements that can validly be used before they appear.
- return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) &&
+ return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
// `var x;` may declare a variable used above
!(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
}
@@ -29447,6 +30130,18 @@ var ts;
}
ts.isInstantiatedModule = isInstantiatedModule;
function createTypeChecker(host, produceDiagnostics) {
+ var getPackagesSet = ts.memoize(function () {
+ var set = ts.createMap();
+ host.getSourceFiles().forEach(function (sf) {
+ if (!sf.resolvedModules)
+ return;
+ ts.forEachEntry(sf.resolvedModules, function (r) {
+ if (r && r.packageId)
+ set.set(r.packageId.name, true);
+ });
+ });
+ return set;
+ });
// Cancellation that controls whether or not we can cancel in the middle of type checking.
// In general cancelling is *not* safe for the type checker. We might be in the middle of
// computing something, and we will leave our internals in an inconsistent state. Callers
@@ -29467,7 +30162,8 @@ var ts;
var typeCount = 0;
var symbolCount = 0;
var enumCount = 0;
- var symbolInstantiationDepth = 0;
+ var instantiationDepth = 0;
+ var constraintDepth = 0;
var emptySymbols = ts.createSymbolTable();
var identityMapper = ts.identity;
var compilerOptions = host.getCompilerOptions();
@@ -29752,7 +30448,8 @@ var ts;
finally {
cancellationToken = undefined;
}
- }
+ },
+ getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
@@ -30123,35 +30820,35 @@ var ts;
function getExcludedSymbolFlags(flags) {
var result = 0;
if (flags & 2 /* BlockScopedVariable */)
- result |= 67216319 /* BlockScopedVariableExcludes */;
+ result |= 67220415 /* BlockScopedVariableExcludes */;
if (flags & 1 /* FunctionScopedVariable */)
- result |= 67216318 /* FunctionScopedVariableExcludes */;
+ result |= 67220414 /* FunctionScopedVariableExcludes */;
if (flags & 4 /* Property */)
result |= 0 /* PropertyExcludes */;
if (flags & 8 /* EnumMember */)
result |= 68008959 /* EnumMemberExcludes */;
if (flags & 16 /* Function */)
- result |= 67215791 /* FunctionExcludes */;
+ result |= 67219887 /* FunctionExcludes */;
if (flags & 32 /* Class */)
result |= 68008383 /* ClassExcludes */;
if (flags & 64 /* Interface */)
- result |= 67901832 /* InterfaceExcludes */;
+ result |= 67897736 /* InterfaceExcludes */;
if (flags & 256 /* RegularEnum */)
result |= 68008191 /* RegularEnumExcludes */;
if (flags & 128 /* ConstEnum */)
result |= 68008831 /* ConstEnumExcludes */;
if (flags & 512 /* ValueModule */)
- result |= 67215503 /* ValueModuleExcludes */;
+ result |= 110735 /* ValueModuleExcludes */;
if (flags & 8192 /* Method */)
- result |= 67208127 /* MethodExcludes */;
+ result |= 67212223 /* MethodExcludes */;
if (flags & 32768 /* GetAccessor */)
- result |= 67150783 /* GetAccessorExcludes */;
+ result |= 67154879 /* GetAccessorExcludes */;
if (flags & 65536 /* SetAccessor */)
- result |= 67183551 /* SetAccessorExcludes */;
+ result |= 67187647 /* SetAccessorExcludes */;
if (flags & 262144 /* TypeParameter */)
- result |= 67639784 /* TypeParameterExcludes */;
+ result |= 67635688 /* TypeParameterExcludes */;
if (flags & 524288 /* TypeAlias */)
- result |= 67901928 /* TypeAliasExcludes */;
+ result |= 67897832 /* TypeAliasExcludes */;
if (flags & 2097152 /* Alias */)
result |= 2097152 /* AliasExcludes */;
return result;
@@ -30197,8 +30894,9 @@ var ts;
target.flags |= source.flags;
if (source.valueDeclaration &&
(!target.valueDeclaration ||
+ ts.isAssignmentDeclaration(target.valueDeclaration) ||
ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) {
- // other kinds of value declarations take precedence over modules
+ // other kinds of value declarations take precedence over modules and assignment declarations
target.valueDeclaration = source.valueDeclaration;
}
ts.addRange(target.declarations, source.declarations);
@@ -30373,8 +31071,8 @@ var ts;
function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
var constructorDeclaration = parameter.parent;
var classDeclaration = parameter.parent.parent;
- var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */);
- var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */);
+ var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */);
+ var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */);
if (parameterSymbol && propertySymbol) {
return [parameterSymbol, propertySymbol];
}
@@ -30517,7 +31215,7 @@ var ts;
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -30526,7 +31224,7 @@ var ts;
// local types not visible outside the function body
: false;
}
- if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) {
+ if (meaning & 67220415 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) {
// parameters are visible only inside function body, parameter list and return type
// technically for parameter list case here we might mix parameters and variables declared in function,
// however it is detected separately when checking initializers of parameters
@@ -30612,7 +31310,7 @@ var ts;
if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) {
var ctor = findConstructorDeclaration(location.parent);
if (ctor && ctor.locals) {
- if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) {
+ if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) {
// Remember the property node, it will be used later to report appropriate error
propertyWithInvalidInitializer = location;
}
@@ -30622,7 +31320,7 @@ var ts;
case 238 /* ClassDeclaration */:
case 207 /* ClassExpression */:
case 239 /* InterfaceDeclaration */:
- if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) {
+ if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67897832 /* Type */)) {
if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
// ignore type parameters not declared in this container
result = undefined;
@@ -30649,7 +31347,7 @@ var ts;
// The type parameters of a class are not in scope in the base class expression.
if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) {
var container = location.parent.parent;
- if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) {
+ if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) {
if (nameNotFoundMessage) {
error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
}
@@ -30669,7 +31367,7 @@ var ts;
grandparent = location.parent.parent;
if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) {
// A reference to this grandparent's type parameters would be an error
- if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) {
+ if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) {
error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
return undefined;
}
@@ -30807,14 +31505,14 @@ var ts;
// we want to check for block-scoped
if (errorLocation &&
(meaning & 2 /* BlockScopedVariable */ ||
- ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) {
+ ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) {
var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
}
}
// If we're in an external module, we can't reference value symbols created from UMD export declarations
- if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) {
+ if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) {
var decls = result.declarations;
if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) {
error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217
@@ -30910,9 +31608,9 @@ var ts;
}
}
function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
- var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0);
+ var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67220415 /* Value */ : 0);
if (meaning === namespaceMeaning) {
- var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
var parent = errorLocation.parent;
if (symbol) {
if (ts.isQualifiedName(parent)) {
@@ -30931,12 +31629,12 @@ var ts;
return false;
}
function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
- if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) {
+ if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) {
if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
return true;
}
- var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
return true;
@@ -30945,15 +31643,15 @@ var ts;
return false;
}
function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
- if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) {
- var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol) {
error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
return true;
}
}
- else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) {
- var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol) {
error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
return true;
@@ -30981,6 +31679,9 @@ var ts;
}
else {
ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
+ if (compilerOptions.preserveConstEnums) {
+ diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
+ }
}
if (diagnosticMessage) {
addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
@@ -31104,7 +31805,7 @@ var ts;
if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
return unknownSymbol;
}
- if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) {
+ if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) {
return valueSymbol;
}
var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
@@ -31194,7 +31895,7 @@ var ts;
if (ts.isClassExpression(expression)) {
return checkExpression(expression).symbol;
}
- var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
+ var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
if (aliasLike) {
return aliasLike;
}
@@ -31213,7 +31914,7 @@ var ts;
case 251 /* ImportSpecifier */:
return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
case 255 /* ExportSpecifier */:
- return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
+ return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
case 252 /* ExportAssignment */:
case 202 /* BinaryExpression */:
return getTargetOfExportAssignment(node, dontRecursivelyResolve);
@@ -31228,7 +31929,7 @@ var ts;
* OR Is a JSContainer which may merge an alias with a local declaration
*/
function isNonLocalAlias(symbol, excludes) {
- if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; }
+ if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; }
if (!symbol)
return false;
return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */);
@@ -31262,7 +31963,7 @@ var ts;
var target = resolveAlias(symbol);
if (target) {
var markAlias = target === unknownSymbol ||
- ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target));
+ ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target));
if (markAlias) {
markAliasSymbolAsReferenced(symbol);
}
@@ -31311,7 +32012,7 @@ var ts;
// Case 2 in above example
// entityName.kind could be a QualifiedName or a Missing identifier
ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */);
- return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
+ return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
}
}
function getFullyQualifiedName(symbol) {
@@ -31324,7 +32025,7 @@ var ts;
if (ts.nodeIsMissing(name)) {
return undefined;
}
- var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0);
+ var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67220415 /* Value */ : 0);
var symbol;
if (name.kind === 71 /* Identifier */) {
var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0;
@@ -31396,8 +32097,20 @@ var ts;
if (ts.isExpressionStatement(host) &&
ts.isBinaryExpression(host.expression) &&
ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) {
+ // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
var symbol = getSymbolOfNode(host.expression.left);
- return symbol && symbol.parent.valueDeclaration;
+ if (symbol) {
+ return getDeclarationOfJSPrototypeContainer(symbol);
+ }
+ }
+ if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
+ ts.isBinaryExpression(host.parent.parent) &&
+ ts.getSpecialPropertyAssignmentKind(host.parent.parent) === 6 /* Prototype */) {
+ // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
+ var symbol = getSymbolOfNode(host.parent.parent.left);
+ if (symbol) {
+ return getDeclarationOfJSPrototypeContainer(symbol);
+ }
}
var sig = ts.getHostSignatureFromJSDocHost(host);
if (sig) {
@@ -31405,6 +32118,13 @@ var ts;
return symbol && symbol.valueDeclaration;
}
}
+ function getDeclarationOfJSPrototypeContainer(symbol) {
+ var decl = symbol.parent.valueDeclaration;
+ var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedJavascriptInitializer(decl) :
+ ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredJavascriptInitializer(decl) :
+ undefined;
+ return initializer || decl;
+ }
function resolveExternalModuleName(location, moduleReferenceExpression) {
return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
}
@@ -31493,7 +32213,7 @@ var ts;
else if (!compilerOptions.resolveJsonModule &&
ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
- ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) {
+ ts.hasJsonModuleEmitEnabled(compilerOptions)) {
error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
}
else {
@@ -31505,18 +32225,17 @@ var ts;
}
function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
- var errorInfo = packageId
- ? ts.chainDiagnosticMessages(
- /*details*/ undefined, typesPackageExists(packageId.name)
- ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1
- : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name))
+ var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
+ ? typesPackageExists(packageId.name)
+ ? ts.chainDiagnosticMessages(
+ /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name))
+ : ts.chainDiagnosticMessages(
+ /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name))
: undefined;
errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
}
function typesPackageExists(packageName) {
- return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) {
- return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName);
- }); });
+ return getPackagesSet().has(ts.getTypesPackageName(packageName));
}
function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol;
@@ -31750,7 +32469,7 @@ var ts;
return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
}
function symbolIsValue(symbol) {
- return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */);
+ return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */);
}
function findConstructorDeclaration(node) {
var members = node.members;
@@ -31850,7 +32569,7 @@ var ts;
}
function getQualifiedLeftMeaning(rightMeaning) {
// If we are looking in value space, the parent meaning is value, other wise it is namespace
- return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */;
+ return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */;
}
function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
@@ -31900,7 +32619,10 @@ var ts;
&& symbolFromSymbolTable.escapedName !== "default" /* Default */
&& !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
// If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
- && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) {
+ && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
+ // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
+ // See similar comment in `resolveName` for details
+ && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) {
var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
return [symbolFromSymbolTable];
@@ -31965,11 +32687,11 @@ var ts;
return false;
}
function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
- var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
+ var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
return access.accessibility === 0 /* Accessible */;
}
function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
- var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
+ var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
return access.accessibility === 0 /* Accessible */;
}
function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
@@ -32007,7 +32729,17 @@ var ts;
// we are going to see if c can be accessed in scope directly.
// But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
// It is accessible if the parent m is accessible because then m.c can be accessed through qualification
- var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
+ var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
+ // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
+ // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
+ // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal.
+ var firstDecl = ts.first(symbol.declarations);
+ if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
+ if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
+ containers = [getSymbolOfNode(firstDecl.parent)];
+ }
+ }
+ var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
if (parentResult) {
return parentResult;
}
@@ -32115,7 +32847,7 @@ var ts;
ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
entityName.parent.kind === 147 /* ComputedPropertyName */) {
// Typeof value
- meaning = 67216319 /* Value */ | 1048576 /* ExportValue */;
+ meaning = 67220415 /* Value */ | 1048576 /* ExportValue */;
}
else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ ||
entityName.parent.kind === 246 /* ImportEqualsDeclaration */) {
@@ -32125,7 +32857,7 @@ var ts;
}
else {
// Type Reference or TypeAlias entity = Identifier
- meaning = 67901928 /* Type */;
+ meaning = 67897832 /* Type */;
}
var firstIdentifier = getFirstIdentifier(entityName);
var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
@@ -32275,13 +33007,13 @@ var ts;
}
if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) {
var parentSymbol = getParentOfSymbol(type.symbol);
- var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false);
+ var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false);
var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol));
context.approximateLength += ts.symbolName(type.symbol).length;
return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined);
}
if (type.flags & 544 /* EnumLike */) {
- var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false);
+ var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false);
context.approximateLength += ts.symbolName(type.symbol).length;
return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined);
}
@@ -32301,7 +33033,7 @@ var ts;
if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
context.approximateLength += 6;
- return symbolToTypeNode(type.symbol, context, 67216319 /* Value */);
+ return symbolToTypeNode(type.symbol, context, 67220415 /* Value */);
}
if (context.tracker.reportInaccessibleUniqueSymbolError) {
context.tracker.reportInaccessibleUniqueSymbolError();
@@ -32368,14 +33100,14 @@ var ts;
}
// Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
return type.symbol
- ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */)
+ ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */)
: ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
}
if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
- return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes);
+ return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes);
}
if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) {
var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types;
@@ -32450,21 +33182,21 @@ var ts;
id = (isConstructorObject ? "+" : "") + getSymbolId(symbol);
if (isJavascriptConstructor(symbol.valueDeclaration)) {
// Instance and static types share the same symbol; only add 'typeof' for the static side.
- var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */;
+ var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */;
return symbolToTypeNode(symbol, context, isInstanceType);
}
// Always use 'typeof T' for type of class, enum, and module objects
else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
shouldWriteTypeOfFunctionSymbol()) {
- return symbolToTypeNode(symbol, context, 67216319 /* Value */);
+ return symbolToTypeNode(symbol, context, 67220415 /* Value */);
}
else if (context.visitedSymbols && context.visitedSymbols.has(id)) {
// If type is an anonymous type literal in a type alias declaration, use type alias name
var typeAlias = getTypeAliasForTypeLiteral(type);
if (typeAlias) {
// The specified symbol flags need to be reinterpreted as type flags
- return symbolToTypeNode(typeAlias, context, 67901928 /* Type */);
+ return symbolToTypeNode(typeAlias, context, 67897832 /* Type */);
}
else {
context.approximateLength += 3;
@@ -32586,7 +33318,7 @@ var ts;
var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
var flags_2 = context.flags;
context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
- var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice);
+ var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice);
context.flags = flags_2;
resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
}
@@ -32599,7 +33331,7 @@ var ts;
}
var flags = context.flags;
context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
- var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes);
+ var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes);
context.flags = flags;
return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
}
@@ -32697,18 +33429,13 @@ var ts;
anyType : getTypeOfSymbol(propertySymbol);
var saveEnclosingDeclaration = context.enclosingDeclaration;
context.enclosingDeclaration = undefined;
- if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) {
+ if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) {
var decl = ts.first(propertySymbol.declarations);
- if (context.tracker.trackSymbol && hasLateBindableName(decl)) {
- // get symbol of the first identifier of the entityName
- var firstIdentifier = getFirstIdentifier(decl.name.expression);
- var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
- if (name) {
- context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */);
- }
+ if (hasLateBindableName(decl)) {
+ trackComputedName(decl.name, saveEnclosingDeclaration, context);
}
}
- var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true);
+ var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true);
context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
context.enclosingDeclaration = saveEnclosingDeclaration;
var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined;
@@ -32836,7 +33563,7 @@ var ts;
return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
}
function typeParameterShadowsNameInScope(type, context) {
- return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false);
+ return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false);
}
function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
var savedContextFlags = context.flags;
@@ -32847,7 +33574,7 @@ var ts;
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */)
- : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true);
+ : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true);
var defaultParameter = getDefaultFromTypeParameter(type);
var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
context.flags = savedContextFlags;
@@ -32888,6 +33615,9 @@ var ts;
function cloneBindingName(node) {
return elideInitializerAndSetEmitFlags(node);
function elideInitializerAndSetEmitFlags(node) {
+ if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
+ trackComputedName(node, context.enclosingDeclaration, context);
+ }
var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
if (clone.kind === 184 /* BindingElement */) {
@@ -32897,6 +33627,16 @@ var ts;
}
}
}
+ function trackComputedName(node, enclosingDeclaration, context) {
+ if (!context.tracker.trackSymbol)
+ return;
+ // get symbol of the first identifier of the entityName
+ var firstIdentifier = getFirstIdentifier(node.expression);
+ var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
+ if (name) {
+ context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */);
+ }
+ }
function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
// Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
@@ -33009,7 +33749,14 @@ var ts;
var links = getSymbolLinks(symbol);
var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
if (!specifier) {
- specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap);
+ var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
+ // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
+ // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
+ // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
+ // specifier preference
+ var moduleResolverHost = context.tracker.moduleResolverHost;
+ var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
+ specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap));
links.specifierCache = links.specifierCache || ts.createMap();
links.specifierCache.set(contextFile.path, specifier);
}
@@ -33017,7 +33764,7 @@ var ts;
}
function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
- var isTypeOf = meaning === 67216319 /* Value */;
+ var isTypeOf = meaning === 67220415 /* Value */;
if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
// module is root, must use `ImportTypeNode`
var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
@@ -33358,10 +34105,10 @@ var ts;
function collectLinkedAliases(node, setVisibility) {
var exportSymbol;
if (node.parent && node.parent.kind === 252 /* ExportAssignment */) {
- exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
+ exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
}
else if (node.parent.kind === 255 /* ExportSpecifier */) {
- exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
+ exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
}
var result;
if (exportSymbol) {
@@ -33382,7 +34129,7 @@ var ts;
// Add the referenced top container visible
var internalModuleReference = declaration.moduleReference;
var firstIdentifier = getFirstIdentifier(internalModuleReference);
- var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
+ var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
if (importSymbol) {
buildVisibleNodeList(importSymbol.declarations);
}
@@ -33714,6 +34461,12 @@ var ts;
return getReturnTypeOfSignature(getterSignature);
}
}
+ if (ts.isInJavaScriptFile(declaration)) {
+ var typeTag = ts.getJSDocType(func);
+ if (typeTag && ts.isFunctionTypeNode(typeTag)) {
+ return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
+ }
+ }
// Use contextual parameter type if one is available
var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
if (type) {
@@ -33804,7 +34557,7 @@ var ts;
return widened;
}
function getJSExpandoObjectType(decl, symbol, init) {
- if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
+ if (!ts.isInJavaScriptFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
return undefined;
}
var exports = ts.createSymbolTable();
@@ -34050,7 +34803,14 @@ var ts;
// Handle export default expressions
if (ts.isSourceFile(declaration)) {
var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile);
- return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType;
+ if (!jsonSourceFile.statements.length) {
+ return emptyObjectType;
+ }
+ var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression));
+ if (type_1.flags & 131072 /* Object */) {
+ return getRegularTypeOfObjectLiteral(type_1);
+ }
+ return type_1;
}
if (declaration.kind === 252 /* ExportAssignment */) {
return checkExpression(declaration.expression);
@@ -34232,11 +34992,11 @@ var ts;
return errorType;
}
var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
- var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
+ var type_2 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
if (!popTypeResolution()) {
return reportCircularityError(symbol);
}
- return type_1;
+ return type_2;
}
}
var type = createObjectType(16 /* Anonymous */, symbol);
@@ -34261,7 +35021,7 @@ var ts;
// type symbol, call getDeclaredTypeOfSymbol.
// This check is important because without it, a call to getTypeOfSymbol could end
// up recursively calling getTypeOfAlias, causing a stack overflow.
- links.type = targetSymbol.flags & 67216319 /* Value */
+ links.type = targetSymbol.flags & 67220415 /* Value */
? getTypeOfSymbol(targetSymbol)
: errorType;
}
@@ -34270,22 +35030,14 @@ var ts;
function getTypeOfInstantiatedSymbol(symbol) {
var links = getSymbolLinks(symbol);
if (!links.type) {
- if (symbolInstantiationDepth === 100) {
- error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite);
- links.type = errorType;
+ if (!pushTypeResolution(symbol, 0 /* Type */)) {
+ return links.type = errorType;
}
- else {
- if (!pushTypeResolution(symbol, 0 /* Type */)) {
- return links.type = errorType;
- }
- symbolInstantiationDepth++;
- var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
- symbolInstantiationDepth--;
- if (!popTypeResolution()) {
- type = reportCircularityError(symbol);
- }
- links.type = type;
+ var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
+ if (!popTypeResolution()) {
+ type = reportCircularityError(symbol);
}
+ links.type = type;
}
return links.type;
}
@@ -34642,7 +35394,7 @@ var ts;
for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
var node = baseTypeNodes_1[_b];
if (ts.isEntityNameExpression(node.expression)) {
- var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true);
+ var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true);
if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
return false;
}
@@ -34781,9 +35533,9 @@ var ts;
if (declaration.kind === 241 /* EnumDeclaration */) {
for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
var member = _c[_b];
- var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217
+ var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217
getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
- memberTypeList.push(memberType);
+ memberTypeList.push(getRegularTypeOfLiteralType(memberType));
}
}
}
@@ -35029,7 +35781,7 @@ var ts;
else {
symbol.declarations.push(member);
}
- if (symbolFlags & 67216319 /* Value */) {
+ if (symbolFlags & 67220415 /* Value */) {
if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
symbol.valueDeclaration = member;
}
@@ -35778,10 +36530,15 @@ var ts;
return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
}
function getConstraintOfIndexedAccess(type) {
- var objectType = getBaseConstraintOfType(type.objectType) || type.objectType;
- var indexType = getBaseConstraintOfType(type.indexType) || type.indexType;
- var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined;
- return constraint && constraint !== errorType ? constraint : undefined;
+ var objectType = getConstraintOfType(type.objectType) || type.objectType;
+ if (objectType !== type.objectType) {
+ var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType);
+ if (constraint && constraint !== errorType) {
+ return constraint;
+ }
+ }
+ var baseConstraint = getBaseConstraintOfType(type);
+ return baseConstraint && baseConstraint !== type ? baseConstraint : undefined;
}
function getDefaultConstraintOfConditionalType(type) {
if (!type.resolvedDefaultConstraint) {
@@ -35798,7 +36555,8 @@ var ts;
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
if (type.root.isDistributive) {
- var constraint = getConstraintOfType(getSimplifiedType(type.checkType));
+ var simplified = getSimplifiedType(type.checkType);
+ var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
if (constraint) {
var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
@@ -35877,6 +36635,7 @@ var ts;
* circularly references the type variable.
*/
function getResolvedBaseConstraint(type) {
+ var nonTerminating = false;
return type.resolvedBaseConstraint ||
(type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
function getImmediateBaseConstraint(t) {
@@ -35884,8 +36643,18 @@ var ts;
if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
return circularConstraintType;
}
+ if (constraintDepth === 50) {
+ // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
+ // very high likelyhood we're dealing with an infinite generic type that perpetually generates
+ // new type identities as we descend into it. We stop the recursion here and mark this type
+ // and the outer types as having circular constraints.
+ nonTerminating = true;
+ return t.immediateBaseConstraint = noConstraintType;
+ }
+ constraintDepth++;
var result = computeBaseConstraint(getSimplifiedType(t));
- if (!popTypeResolution()) {
+ constraintDepth--;
+ if (!popTypeResolution() || nonTerminating) {
result = circularConstraintType;
}
t.immediateBaseConstraint = result || noConstraintType;
@@ -35907,8 +36676,8 @@ var ts;
var types = t.types;
var baseTypes = [];
for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
- var type_2 = types_4[_i];
- var baseType = getBaseConstraint(type_2);
+ var type_3 = types_4[_i];
+ var baseType = getBaseConstraint(type_3);
if (baseType) {
baseTypes.push(baseType);
}
@@ -35923,7 +36692,7 @@ var ts;
if (t.flags & 2097152 /* IndexedAccess */) {
var baseObjectType = getBaseConstraint(t.objectType);
var baseIndexType = getBaseConstraint(t.indexType);
- var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined;
+ var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined;
return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 4194304 /* Conditional */) {
@@ -35933,9 +36702,6 @@ var ts;
if (t.flags & 8388608 /* Substitution */) {
return getBaseConstraint(t.substitute);
}
- if (isGenericMappedType(t)) {
- return emptyObjectType;
- }
return t;
}
}
@@ -35985,6 +36751,20 @@ var ts;
function hasTypeParameterDefault(typeParameter) {
return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
}
+ function getApparentTypeOfMappedType(type) {
+ return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
+ }
+ function getResolvedApparentTypeOfMappedType(type) {
+ var typeVariable = getHomomorphicTypeVariable(type);
+ if (typeVariable) {
+ var constraint = getConstraintOfTypeParameter(typeVariable);
+ if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) {
+ var mapper = makeUnaryTypeMapper(typeVariable, constraint);
+ return instantiateType(type, combineTypeMappers(mapper, type.mapper));
+ }
+ }
+ return type;
+ }
/**
* For a type parameter, return the base constraint of the type parameter. For the string, number,
* boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
@@ -35992,14 +36772,15 @@ var ts;
*/
function getApparentType(type) {
var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type;
- return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
- t.flags & 68 /* StringLike */ ? globalStringType :
- t.flags & 168 /* NumberLike */ ? globalNumberType :
- t.flags & 272 /* BooleanLike */ ? globalBooleanType :
- t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
- t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType :
- t.flags & 1048576 /* Index */ ? keyofConstraintType :
- t;
+ return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
+ t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
+ t.flags & 68 /* StringLike */ ? globalStringType :
+ t.flags & 168 /* NumberLike */ ? globalNumberType :
+ t.flags & 272 /* BooleanLike */ ? globalBooleanType :
+ t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
+ t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType :
+ t.flags & 1048576 /* Index */ ? keyofConstraintType :
+ t;
}
function createUnionOrIntersectionProperty(containingType, name) {
var props;
@@ -36318,7 +37099,7 @@ var ts;
var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
// Include parameter symbol instead of property symbol in the signature
if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
- var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false);
+ var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false);
paramSymbol = resolvedSymbol;
}
if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
@@ -36569,8 +37350,12 @@ var ts;
return tryGetRestTypeOfSignature(signature) || anyType;
}
function tryGetRestTypeOfSignature(signature) {
- var type = getTypeOfRestParameter(signature);
- return type && getIndexTypeOfType(type, 1 /* Number */);
+ if (signature.hasRestParameter) {
+ var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
+ var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
+ return restType && getIndexTypeOfType(restType, 1 /* Number */);
+ }
+ return undefined;
}
function getSignatureInstantiation(signature, typeArguments, isJavascript) {
return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
@@ -36893,14 +37678,19 @@ var ts;
if (type) {
return type;
}
+ // JS are 'string' or 'number', not an enum type.
+ var enumTag = symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration);
+ if (enumTag) {
+ return enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType;
+ }
// Get type from reference to named type that cannot be generic (enum or type parameter)
var res = tryGetDeclaredTypeOfSymbol(symbol);
if (res) {
return checkNoTypeArguments(node, symbol) ?
- res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res :
+ res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) :
errorType;
}
- if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) {
+ if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) {
return errorType;
}
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
@@ -36908,7 +37698,7 @@ var ts;
return jsdocType;
}
// Resolve the type reference as a Type for the purpose of reporting errors.
- resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */);
+ resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */);
return getTypeOfSymbol(symbol);
}
/**
@@ -36924,10 +37714,6 @@ var ts;
// TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?)
return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType);
}
- var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration);
- if (enumTag && enumTag.typeExpression) {
- return getTypeFromTypeNode(enumTag.typeExpression);
- }
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
@@ -37042,10 +37828,10 @@ var ts;
if (!links.resolvedType) {
var symbol = void 0;
var type = void 0;
- var meaning = 67901928 /* Type */;
+ var meaning = 67897832 /* Type */;
if (isJSDocTypeReference(node)) {
type = getIntendedTypeFromJSDocTypeReference(node);
- meaning |= 67216319 /* Value */;
+ meaning |= 67220415 /* Value */;
}
if (!type) {
symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
@@ -37100,10 +37886,10 @@ var ts;
return type;
}
function getGlobalValueSymbol(name, reportErrors) {
- return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
+ return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
}
function getGlobalTypeSymbol(name, reportErrors) {
- return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
+ return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
}
function getGlobalSymbol(name, meaning, diagnostic) {
// Don't track references for global symbols anyway, so value if `isReference` is arbitrary
@@ -37157,7 +37943,7 @@ var ts;
}
function getGlobalTypeOrUndefined(name, arity) {
if (arity === void 0) { arity = 0; }
- var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined);
+ var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined);
return symbol && getTypeOfGlobalSymbol(symbol, arity);
}
function getGlobalExtractSymbol() {
@@ -37346,10 +38132,7 @@ var ts;
var len = typeSet.length;
var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
if (index < 0) {
- if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ &&
- type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) {
- typeSet.splice(~index, 0, type);
- }
+ typeSet.splice(~index, 0, type);
}
}
}
@@ -37364,15 +38147,6 @@ var ts;
}
return includes;
}
- function containsIdenticalType(types, type) {
- for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
- var t = types_7[_i];
- if (isTypeIdenticalTo(t, type)) {
- return true;
- }
- }
- return false;
- }
function isSubtypeOfAny(source, targets) {
for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
var target = targets_1[_i];
@@ -37543,10 +38317,7 @@ var ts;
if (type === wildcardType)
includes |= 268435456 /* Wildcard */;
}
- else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) &&
- !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ &&
- type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) &&
- containsIdenticalType(typeSet, type))) {
+ else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) {
typeSet.push(type);
}
}
@@ -37555,8 +38326,8 @@ var ts;
// Add the given types to the given type set. Order is preserved, freshness is removed from literal
// types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet, includes, types) {
- for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
- var type = types_8[_i];
+ for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
+ var type = types_7[_i];
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
@@ -37810,7 +38581,7 @@ var ts;
}
return false;
}
- function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) {
+ function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) {
var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined;
var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) :
accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
@@ -37823,7 +38594,7 @@ var ts;
markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */);
if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) {
error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop));
- return errorType;
+ return missingType;
}
if (cacheSymbol) {
getNodeLinks(accessNode).resolvedSymbol = prop;
@@ -37882,7 +38653,7 @@ var ts;
}
}
}
- return anyType;
+ return missingType;
}
}
if (isJSLiteralType(objectType)) {
@@ -37900,7 +38671,10 @@ var ts;
error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
}
}
- return errorType;
+ if (isTypeAny(indexType)) {
+ return indexType;
+ }
+ return missingType;
}
function isGenericObjectType(type) {
return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */);
@@ -37908,20 +38682,6 @@ var ts;
function isGenericIndexType(type) {
return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */);
}
- // Return true if the given type is a non-generic object type with a string index signature and no
- // other members.
- function isStringIndexOnlyType(type) {
- if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) {
- var t = resolveStructuredTypeMembers(type);
- return t.properties.length === 0 &&
- t.callSignatures.length === 0 && t.constructSignatures.length === 0 &&
- !!t.stringIndexInfo && !t.numberIndexInfo;
- }
- return false;
- }
- function isMappedTypeToNever(type) {
- return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType;
- }
function getSimplifiedType(type) {
return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type;
}
@@ -37935,36 +38695,12 @@ var ts;
// We recursively simplify the object type as it may in turn be an indexed access type. For example, with
// '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
var objectType = getSimplifiedType(type.objectType);
- if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) {
- // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or
- // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a
- // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed
- // access types with default property values as expressed by D.
- if (ts.some(objectType.types, isStringIndexOnlyType)) {
- var regularTypes = [];
- var stringIndexTypes = [];
- for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) {
- var t = _a[_i];
- if (isStringIndexOnlyType(t)) {
- stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */));
- }
- else {
- regularTypes.push(t);
- }
- }
- return type.simplified = getUnionType([
- getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)),
- getIntersectionType(stringIndexTypes)
- ]);
- }
- // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or
- // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a
- // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen
- // eventually anyway, but it easier to reason about.
- if (ts.some(objectType.types, isMappedTypeToNever)) {
- var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); });
- return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType));
- }
+ var indexType = getSimplifiedType(type.indexType);
+ if (objectType.flags & 262144 /* Union */) {
+ return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); });
+ }
+ if (objectType.flags & 524288 /* Intersection */) {
+ return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }));
}
// If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
// that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we
@@ -37986,7 +38722,8 @@ var ts;
var templateMapper = combineTypeMappers(objectType.mapper, mapper);
return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
}
- function getIndexedAccessType(objectType, indexType, accessNode) {
+ function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
+ if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; }
if (objectType === wildcardType || indexType === wildcardType) {
return wildcardType;
}
@@ -38013,17 +38750,28 @@ var ts;
var apparentObjectType = getApparentType(objectType);
if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
var propTypes = [];
+ var wasMissingProp = false;
for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
var t = _a[_i];
- var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false);
- if (propType === errorType) {
- return errorType;
+ var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType);
+ if (propType === missingType) {
+ if (!accessNode) {
+ // If there's no error node, we can immeditely stop, since error reporting is off
+ return missingType;
+ }
+ else {
+ // Otherwise we set a flag and return at the end of the loop so we still mark all errors
+ wasMissingProp = true;
+ }
}
propTypes.push(propType);
}
+ if (wasMissingProp) {
+ return missingType;
+ }
return getUnionType(propTypes);
}
- return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true);
+ return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType);
}
function getTypeFromIndexedAccessTypeNode(node) {
var links = getNodeLinks(node);
@@ -38201,7 +38949,7 @@ var ts;
links.resolvedSymbol = unknownSymbol;
return links.resolvedType = errorType;
}
- var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */;
+ var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */;
// TODO: Future work: support unions/generics/whatever via a deferred import-type
var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
if (!innerModuleSymbol) {
@@ -38231,7 +38979,7 @@ var ts;
resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
}
else {
- var errorMessage = targetMeaning === 67216319 /* Value */
+ var errorMessage = targetMeaning === 67220415 /* Value */
? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
: ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
error(node, errorMessage, node.argument.literal.text);
@@ -38245,7 +38993,7 @@ var ts;
function resolveImportSymbolType(node, links, symbol, meaning) {
var resolvedSymbol = resolveSymbol(symbol);
links.resolvedSymbol = resolvedSymbol;
- if (meaning === 67216319 /* Value */) {
+ if (meaning === 67220415 /* Value */) {
return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
}
else {
@@ -38604,7 +39352,7 @@ var ts;
}
function cloneTypeMapper(mapper) {
return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
+ createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
mapper;
}
function combineTypeMappers(mapper1, mapper2) {
@@ -38774,8 +39522,18 @@ var ts;
return !!ts.forEachChild(node, containsReference);
}
}
+ function getHomomorphicTypeVariable(type) {
+ var constraintType = getConstraintTypeFromMappedType(type);
+ if (constraintType.flags & 1048576 /* Index */) {
+ var typeVariable = constraintType.type;
+ if (typeVariable.flags & 65536 /* TypeParameter */) {
+ return typeVariable;
+ }
+ }
+ return undefined;
+ }
function instantiateMappedType(type, mapper) {
- // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
+ // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
// operation depends on T as follows:
// * If T is a primitive type no mapping is performed and the result is simply T.
// * If T is a union type we distribute the mapped type over the union.
@@ -38785,30 +39543,24 @@ var ts;
// For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
// { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
// { [P in keyof A]: X } | undefined.
- var constraintType = getConstraintTypeFromMappedType(type);
- if (constraintType.flags & 1048576 /* Index */) {
- var typeVariable_1 = constraintType.type;
- if (typeVariable_1.flags & 65536 /* TypeParameter */) {
- var mappedTypeVariable = instantiateType(typeVariable_1, mapper);
- if (typeVariable_1 !== mappedTypeVariable) {
- return mapType(mappedTypeVariable, function (t) {
- if (isMappableType(t)) {
- var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper);
- return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
- isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
- isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
- instantiateAnonymousType(type, replacementMapper);
- }
- return t;
- });
- }
+ var typeVariable = getHomomorphicTypeVariable(type);
+ if (typeVariable) {
+ var mappedTypeVariable = instantiateType(typeVariable, mapper);
+ if (typeVariable !== mappedTypeVariable) {
+ return mapType(mappedTypeVariable, function (t) {
+ if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) {
+ var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
+ return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
+ isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
+ isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
+ instantiateAnonymousType(type, replacementMapper);
+ }
+ return t;
+ });
}
}
return instantiateAnonymousType(type, mapper);
}
- function isMappableType(type) {
- return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */);
- }
function instantiateMappedTupleType(tupleType, mappedType, mapper) {
var minLength = tupleType.target.minLength;
var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
@@ -38871,49 +39623,65 @@ var ts;
return getConditionalType(root, mapper);
}
function instantiateType(type, mapper) {
- if (type && mapper && mapper !== identityMapper) {
- if (type.flags & 65536 /* TypeParameter */) {
- return mapper(type);
+ if (!type || !mapper || mapper === identityMapper) {
+ return type;
+ }
+ if (instantiationDepth === 50) {
+ // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
+ // with a combination of infinite generic types that perpetually generate new type identities. We stop
+ // the recursion here by yielding the error type.
+ return errorType;
+ }
+ instantiationDepth++;
+ var result = instantiateTypeWorker(type, mapper);
+ instantiationDepth--;
+ return result;
+ }
+ function instantiateTypeWorker(type, mapper) {
+ var flags = type.flags;
+ if (flags & 65536 /* TypeParameter */) {
+ return mapper(type);
+ }
+ if (flags & 131072 /* Object */) {
+ var objectFlags = type.objectFlags;
+ if (objectFlags & 16 /* Anonymous */) {
+ // If the anonymous type originates in a declaration of a function, method, class, or
+ // interface, in an object type literal, or in an object literal expression, we may need
+ // to instantiate the type because it might reference a type parameter.
+ return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ?
+ getAnonymousTypeInstantiation(type, mapper) : type;
}
- if (type.flags & 131072 /* Object */) {
- if (type.objectFlags & 16 /* Anonymous */) {
- // If the anonymous type originates in a declaration of a function, method, class, or
- // interface, in an object type literal, or in an object literal expression, we may need
- // to instantiate the type because it might reference a type parameter.
- return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ?
- getAnonymousTypeInstantiation(type, mapper) : type;
- }
- if (type.objectFlags & 32 /* Mapped */) {
- return getAnonymousTypeInstantiation(type, mapper);
- }
- if (type.objectFlags & 4 /* Reference */) {
- var typeArguments = type.typeArguments;
- var newTypeArguments = instantiateTypes(typeArguments, mapper);
- return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type;
- }
+ if (objectFlags & 32 /* Mapped */) {
+ return getAnonymousTypeInstantiation(type, mapper);
}
- if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) {
- var types = type.types;
- var newTypes = instantiateTypes(types, mapper);
- return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
- }
- if (type.flags & 524288 /* Intersection */) {
- var types = type.types;
- var newTypes = instantiateTypes(types, mapper);
- return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
- }
- if (type.flags & 1048576 /* Index */) {
- return getIndexType(instantiateType(type.type, mapper));
- }
- if (type.flags & 2097152 /* IndexedAccess */) {
- return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
- }
- if (type.flags & 4194304 /* Conditional */) {
- return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
- }
- if (type.flags & 8388608 /* Substitution */) {
- return instantiateType(type.typeVariable, mapper);
+ if (objectFlags & 4 /* Reference */) {
+ var typeArguments = type.typeArguments;
+ var newTypeArguments = instantiateTypes(typeArguments, mapper);
+ return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type;
}
+ return type;
+ }
+ if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) {
+ var types = type.types;
+ var newTypes = instantiateTypes(types, mapper);
+ return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
+ }
+ if (flags & 524288 /* Intersection */) {
+ var types = type.types;
+ var newTypes = instantiateTypes(types, mapper);
+ return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
+ }
+ if (flags & 1048576 /* Index */) {
+ return getIndexType(instantiateType(type.type, mapper));
+ }
+ if (flags & 2097152 /* IndexedAccess */) {
+ return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
+ }
+ if (flags & 4194304 /* Conditional */) {
+ return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
+ }
+ if (flags & 8388608 /* Substitution */) {
+ return instantiateType(type.typeVariable, mapper);
}
return type;
}
@@ -39062,15 +39830,21 @@ var ts;
* attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
*/
function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
- if (isTypeAssignableTo(source, target))
+ return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain);
+ }
+ function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) {
+ if (isTypeRelatedTo(source, target, relation))
return true;
- if (!elaborateError(expr, source, target)) {
- return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain);
+ if (!errorNode || !elaborateError(expr, source, target)) {
+ return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain);
}
return false;
}
+ function isOrHasGenericConditional(type) {
+ return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
+ }
function elaborateError(node, source, target) {
- if (!node)
+ if (!node || isOrHasGenericConditional(target))
return false;
switch (node.kind) {
case 268 /* JsxExpression */:
@@ -39102,9 +39876,9 @@ var ts;
var reportedError = false;
for (var status = iterator.next(); !status.done; status = iterator.next()) {
var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
- var sourcePropType = getIndexedAccessType(source, nameType);
- var targetPropType = getIndexedAccessType(target, nameType);
- if (!isTypeAssignableTo(sourcePropType, targetPropType)) {
+ var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType);
+ var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType);
+ if (sourcePropType !== errorType && targetPropType !== errorType && !isTypeAssignableTo(sourcePropType, targetPropType)) {
var elaborated = next && elaborateError(next, sourcePropType, targetPropType);
if (elaborated) {
reportedError = true;
@@ -39283,9 +40057,10 @@ var ts;
source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes);
}
var sourceCount = getParameterCount(source);
- var sourceGenericRestType = getGenericRestType(source);
- var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined;
- if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) {
+ var sourceRestType = getNonArrayRestType(source);
+ var targetRestType = getNonArrayRestType(target);
+ if (sourceRestType && targetRestType && sourceCount !== targetCount) {
+ // We're not able to relate misaligned complex rest parameters
return 0 /* False */;
}
var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
@@ -39308,11 +40083,11 @@ var ts;
result &= related;
}
}
- var paramCount = Math.max(sourceCount, targetCount);
- var lastIndex = paramCount - 1;
+ var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
+ var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
for (var i = 0; i < paramCount; i++) {
- var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i);
- var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i);
+ var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
+ var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
// In order to ensure that any generic type Foo is at least co-variant with respect to T no matter
// how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
// they naturally relate only contra-variantly). However, if the source and target parameters both have
@@ -39705,13 +40480,10 @@ var ts;
source = getRegularTypeOfObjectLiteral(source);
}
}
- if (relation !== comparableRelation &&
- !(source.flags & 786432 /* UnionOrIntersection */) &&
- !(target.flags & 262144 /* Union */) &&
- !isIntersectionConstituent &&
- source !== globalObjectType &&
+ if (relation !== comparableRelation && !isIntersectionConstituent &&
+ source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType &&
+ target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) &&
(getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) &&
- isWeakType(target) &&
!hasCommonProperties(source, target)) {
if (reportErrors) {
var calls = getSignaturesOfType(source, 0 /* Call */);
@@ -39810,7 +40582,7 @@ var ts;
function isIdenticalTo(source, target) {
var result;
var flags = source.flags & target.flags;
- if (flags & 131072 /* Object */) {
+ if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) {
return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false);
}
if (flags & (262144 /* Union */ | 524288 /* Intersection */)) {
@@ -39820,32 +40592,6 @@ var ts;
}
}
}
- if (flags & 1048576 /* Index */) {
- return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
- }
- if (flags & 2097152 /* IndexedAccess */) {
- if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
- return result;
- }
- }
- }
- if (flags & 4194304 /* Conditional */) {
- if (source.root.isDistributive === target.root.isDistributive) {
- if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
- if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
- return result;
- }
- }
- }
- }
- }
- }
- if (flags & 8388608 /* Substitution */) {
- return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
- }
return 0 /* False */;
}
function hasExcessProperties(source, target, discriminant, reportErrors) {
@@ -39863,7 +40609,7 @@ var ts;
return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors);
}
var _loop_5 = function (prop) {
- if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
+ if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
if (reportErrors) {
// We know *exactly* where things went wrong when comparing the types.
// Use this property as the error node as this will be more helpful in
@@ -39908,6 +40654,9 @@ var ts;
}
return false;
}
+ function isPropertyFromSpread(prop, container) {
+ return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration;
+ }
function eachTypeRelatedToSomeType(source, target) {
var result = -1 /* True */;
var sourceTypes = source.types;
@@ -39936,7 +40685,8 @@ var ts;
if (reportErrors) {
var bestMatchingType = findMatchingDiscriminantType(source, target) ||
findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
- findBestTypeForObjectLiteral(source, target);
+ findBestTypeForObjectLiteral(source, target) ||
+ findBestTypeForInvokable(source, target);
isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
}
return 0 /* False */;
@@ -39963,6 +40713,14 @@ var ts;
return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
}
}
+ function findBestTypeForInvokable(source, unionTarget) {
+ var signatureKind = 0 /* Call */;
+ var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
+ (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
+ if (hasSignatures) {
+ return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
+ }
+ }
// Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
function findMatchingDiscriminantType(source, target) {
var match;
@@ -40153,6 +40911,37 @@ var ts;
return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type);
}
function structuredTypeRelatedTo(source, target, reportErrors) {
+ var flags = source.flags & target.flags;
+ if (relation === identityRelation && !(flags & 131072 /* Object */)) {
+ if (flags & 1048576 /* Index */) {
+ return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
+ }
+ var result_2 = 0 /* False */;
+ if (flags & 2097152 /* IndexedAccess */) {
+ if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
+ if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
+ return result_2;
+ }
+ }
+ }
+ if (flags & 4194304 /* Conditional */) {
+ if (source.root.isDistributive === target.root.isDistributive) {
+ if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
+ if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
+ if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ return result_2;
+ }
+ }
+ }
+ }
+ }
+ }
+ if (flags & 8388608 /* Substitution */) {
+ return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
+ }
+ return 0 /* False */;
+ }
var result;
var originalErrorInfo;
var saveErrorInfo = errorInfo;
@@ -40188,13 +40977,13 @@ var ts;
}
}
else if (target.flags & 2097152 /* IndexedAccess */) {
- // A type S is related to a type T[K] if S is related to C, where C is the
- // constraint of T[K]
- var constraint = getConstraintForRelation(target);
- if (constraint) {
- if (result = isRelatedTo(source, constraint, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
+ // A type S is related to a type T[K] if S is related to C, where C is the base constraint of T[K]
+ if (relation !== identityRelation) {
+ var constraint = getBaseConstraintOfType(target);
+ if (constraint && constraint !== target) {
+ if (result = isRelatedTo(source, constraint, reportErrors)) {
+ return result;
+ }
}
}
}
@@ -40212,7 +41001,6 @@ var ts;
var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
var templateType = getTemplateTypeFromMappedType(target);
if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
- errorInfo = saveErrorInfo;
return result;
}
}
@@ -40285,6 +41073,26 @@ var ts;
}
}
else {
+ // An empty object type is related to any mapped type that includes a '?' modifier.
+ if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) {
+ return -1 /* True */;
+ }
+ if (isGenericMappedType(target)) {
+ if (isGenericMappedType(source)) {
+ if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ return 0 /* False */;
+ }
+ if (relation === definitelyAssignableRelation && isGenericMappedType(source)) {
+ return 0 /* False */;
+ }
+ var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */);
+ if (relation !== identityRelation) {
+ source = getApparentType(source);
+ }
if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
!(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
// We have type references to the same generic type, and the type references are not marker
@@ -40318,36 +41126,26 @@ var ts;
errorInfo = saveErrorInfo;
}
}
+ else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) {
+ return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
+ }
// Even if relationship doesn't hold for unions, intersections, or generic type references,
// it may hold in a structural comparison.
- var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */);
- if (relation !== identityRelation) {
- source = getApparentType(source);
- }
// In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
// to X. Failing both of those we want to check if the aggregation of A and B's members structurally
// relates to X. Thus, we include intersection types on the source side here.
if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) {
// Report structural errors only if we haven't reported any errors yet
var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive;
- // An empty object type is related to any mapped type that includes a '?' modifier.
- if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) {
- result = -1 /* True */;
- }
- else if (isGenericMappedType(target)) {
- result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */;
- }
- else {
- result = propertiesRelatedTo(source, target, reportStructuralErrors);
+ result = propertiesRelatedTo(source, target, reportStructuralErrors);
+ if (result) {
+ result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
if (result) {
- result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
+ result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
if (result) {
- result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
+ result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors);
if (result) {
- result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors);
- if (result) {
- result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors);
- }
+ result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors);
}
}
}
@@ -40370,10 +41168,10 @@ var ts;
var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
if (modifiersRelated) {
- var result_2;
- if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
+ var result_3;
+ if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
- return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
+ return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
}
}
return 0 /* False */;
@@ -40504,33 +41302,6 @@ var ts;
}
return result;
}
- /**
- * A type is 'weak' if it is an object type with at least one optional property
- * and no required properties, call/construct signatures or index signatures
- */
- function isWeakType(type) {
- if (type.flags & 131072 /* Object */) {
- var resolved = resolveStructuredTypeMembers(type);
- return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
- !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
- resolved.properties.length > 0 &&
- ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
- }
- if (type.flags & 524288 /* Intersection */) {
- return ts.every(type.types, isWeakType);
- }
- return false;
- }
- function hasCommonProperties(source, target) {
- var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
- for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
- var prop = _a[_i];
- if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
- return true;
- }
- }
- return false;
- }
function propertiesIdenticalTo(source, target) {
if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) {
return 0 /* False */;
@@ -40755,6 +41526,33 @@ var ts;
return false;
}
}
+ /**
+ * A type is 'weak' if it is an object type with at least one optional property
+ * and no required properties, call/construct signatures or index signatures
+ */
+ function isWeakType(type) {
+ if (type.flags & 131072 /* Object */) {
+ var resolved = resolveStructuredTypeMembers(type);
+ return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
+ !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
+ resolved.properties.length > 0 &&
+ ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
+ }
+ if (type.flags & 524288 /* Intersection */) {
+ return ts.every(type.types, isWeakType);
+ }
+ return false;
+ }
+ function hasCommonProperties(source, target) {
+ var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
+ for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
+ var prop = _a[_i];
+ if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
+ return true;
+ }
+ }
+ return false;
+ }
// Return a type reference where the source type parameter is replaced with the target marker
// type, and flag the result as a marker type reference.
function getMarkerTypeReference(type, source, target) {
@@ -41043,8 +41841,8 @@ var ts;
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
- var t = types_9[_i];
+ for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
+ var t = types_8[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
@@ -41120,7 +41918,7 @@ var ts;
type;
}
function getWidenedLiteralType(type) {
- return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
+ return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType :
type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType :
type.flags & 256 /* BooleanLiteral */ ? booleanType :
@@ -41148,13 +41946,17 @@ var ts;
function getRestTypeOfTupleType(type) {
return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined;
}
+ function getRestArrayTypeOfTupleType(type) {
+ var restType = getRestTypeOfTupleType(type);
+ return restType && createArrayType(restType);
+ }
function getLengthOfTupleType(type) {
return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
- var t = types_10[_i];
+ for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
+ var t = types_9[_i];
result |= getFalsyFlags(t);
}
return result;
@@ -41470,19 +42272,23 @@ var ts;
function forEachMatchingParameterType(source, target, callback) {
var sourceCount = getParameterCount(source);
var targetCount = getParameterCount(target);
- var sourceHasRest = hasEffectiveRestParameter(source);
- var targetHasRest = hasEffectiveRestParameter(target);
- var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) :
- sourceHasRest ? targetCount :
- targetHasRest ? sourceCount :
- Math.min(sourceCount, targetCount);
- var targetGenericRestType = getGenericRestType(target);
- var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount;
+ var sourceRestType = getEffectiveRestType(source);
+ var targetRestType = getEffectiveRestType(target);
+ var paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) :
+ sourceRestType ? targetCount :
+ Math.min(sourceCount, targetCount);
+ var sourceThisType = getThisTypeOfSignature(source);
+ if (sourceThisType) {
+ var targetThisType = getThisTypeOfSignature(target);
+ if (targetThisType) {
+ callback(sourceThisType, targetThisType);
+ }
+ }
for (var i = 0; i < paramCount; i++) {
callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
}
- if (targetGenericRestType) {
- callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType);
+ if (targetRestType) {
+ callback(getRestTypeAtPosition(source, paramCount), targetRestType);
}
}
function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
@@ -41928,33 +42734,38 @@ var ts;
}
}
function inferFromProperties(source, target) {
- if (isTupleType(source) && isTupleType(target)) {
- var sourceLength = getLengthOfTupleType(source);
- var targetLength = getLengthOfTupleType(target);
- var sourceRestType = getRestTypeOfTupleType(source);
- var targetRestType = getRestTypeOfTupleType(target);
- var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
- for (var i = 0; i < fixedLength; i++) {
- inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]);
+ if (isTupleType(source)) {
+ if (isTupleType(target)) {
+ var sourceLength = getLengthOfTupleType(source);
+ var targetLength = getLengthOfTupleType(target);
+ var sourceRestType = getRestTypeOfTupleType(source);
+ var targetRestType = getRestTypeOfTupleType(target);
+ var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
+ for (var i = 0; i < fixedLength; i++) {
+ inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]);
+ }
+ if (targetRestType) {
+ var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : [];
+ if (sourceRestType) {
+ types.push(sourceRestType);
+ }
+ if (types.length) {
+ inferFromTypes(getUnionType(types), targetRestType);
+ }
+ }
+ return;
}
- if (targetRestType) {
- var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : [];
- if (sourceRestType) {
- types.push(sourceRestType);
- }
- if (types.length) {
- inferFromTypes(getUnionType(types), targetRestType);
- }
+ if (isArrayType(target)) {
+ inferFromIndexTypes(source, target);
+ return;
}
}
- else {
- var properties = getPropertiesOfObjectType(target);
- for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
- var targetProp = properties_6[_i];
- var sourceProp = getPropertyOfType(source, targetProp.escapedName);
- if (sourceProp) {
- inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
- }
+ var properties = getPropertiesOfObjectType(target);
+ for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
+ var targetProp = properties_6[_i];
+ var sourceProp = getPropertyOfType(source, targetProp.escapedName);
+ if (sourceProp) {
+ inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
}
}
}
@@ -41964,12 +42775,15 @@ var ts;
var sourceLen = sourceSignatures.length;
var targetLen = targetSignatures.length;
var len = sourceLen < targetLen ? sourceLen : targetLen;
+ var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */);
for (var i = 0; i < len; i++) {
- inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]));
+ inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
}
}
- function inferFromSignature(source, target) {
- forEachMatchingParameterType(source, target, inferFromContravariantTypes);
+ function inferFromSignature(source, target, skipParameters) {
+ if (!skipParameters) {
+ forEachMatchingParameterType(source, target, inferFromContravariantTypes);
+ }
var sourceTypePredicate = getTypePredicateOfSignature(source);
var targetTypePredicate = getTypePredicateOfSignature(target);
if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) {
@@ -42000,8 +42814,8 @@ var ts;
}
}
function typeIdenticalToSomeType(type, types) {
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var t = types_11[_i];
+ for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
+ var t = types_10[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -42042,7 +42856,7 @@ var ts;
function getContravariantInference(inference) {
return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
}
- function getCovariantInference(inference, context, signature) {
+ function getCovariantInference(inference, signature) {
// Extract all object literal types and replace them with a single widened and normalized type.
var candidates = widenObjectLiteralCandidates(inference.candidates);
// We widen inferred literal types if
@@ -42055,10 +42869,9 @@ var ts;
var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
candidates;
- // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if
- // union types were requested or if all inferences were made from the return type position, infer a
- // union type. Otherwise, infer a common supertype.
- var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ?
+ // If all inferences were made from a position that implies a combined result, infer a union type.
+ // Otherwise, infer a common supertype.
+ var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ?
getUnionType(baseCandidates, 2 /* Subtype */) :
getCommonSupertype(baseCandidates);
return getWidenedType(unwidenedType);
@@ -42069,16 +42882,17 @@ var ts;
if (!inferredType) {
var signature = context.signature;
if (signature) {
- if (inference.contraCandidates) {
- // If we have contravariant inferences we find the best common subtype and treat
- // that as a single covariant candidate.
- inference.candidates = ts.append(inference.candidates, getContravariantInference(inference));
+ if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & 32768 /* Never */)) {
+ // If we have contravariant inferences, but no covariant inferences or a single
+ // covariant inference of 'never', we find the best common subtype and treat that
+ // as a single covariant candidate.
+ inference.candidates = [getContravariantInference(inference)];
inference.contraCandidates = undefined;
}
if (inference.candidates) {
- inferredType = getCovariantInference(inference, context, signature);
+ inferredType = getCovariantInference(inference, signature);
}
- else if (context.flags & 2 /* NoDefault */) {
+ else if (context.flags & 1 /* NoDefault */) {
// We use silentNeverType as the wildcard that signals no inferences.
inferredType = silentNeverType;
}
@@ -42095,7 +42909,7 @@ var ts;
inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
}
else {
- inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */));
+ inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
}
}
}
@@ -42128,7 +42942,7 @@ var ts;
var links = getNodeLinks(node);
if (!links.resolvedSymbol) {
links.resolvedSymbol = !ts.nodeIsMissing(node) &&
- resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node),
+ resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node),
/*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
}
return links.resolvedSymbol;
@@ -42302,6 +43116,18 @@ var ts;
}
return flow.id;
}
+ function typeMaybeAssignableTo(source, target) {
+ if (!(source.flags & 262144 /* Union */)) {
+ return isTypeAssignableTo(source, target);
+ }
+ for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
+ var t = _a[_i];
+ if (isTypeAssignableTo(t, target)) {
+ return true;
+ }
+ }
+ return false;
+ }
// Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
// For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
// we remove type string.
@@ -42310,8 +43136,12 @@ var ts;
if (assignedType.flags & 32768 /* Never */) {
return assignedType;
}
- var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); });
- if (!(reducedType.flags & 32768 /* Never */)) {
+ var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
+ // Our crude heuristic produces an invalid result in some cases: see GH#26130.
+ // For now, when that happens, we give up and don't narrow at all. (This also
+ // means we'll never narrow for erroneous assignments where the assigned type
+ // is not assignable to the declared type.)
+ if (isTypeAssignableTo(assignedType, reducedType)) {
return reducedType;
}
}
@@ -42319,8 +43149,8 @@ var ts;
}
function getTypeFactsOfTypes(types) {
var result = 0 /* None */;
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var t = types_12[_i];
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var t = types_11[_i];
result |= getTypeFacts(t);
}
return result;
@@ -42489,10 +43319,10 @@ var ts;
getInitialTypeOfVariableDeclaration(node) :
getInitialTypeOfBindingElement(node);
}
- function getInitialOrAssignedType(node) {
- return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ?
+ function getInitialOrAssignedType(node, reference) {
+ return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ?
getInitialType(node) :
- getAssignedType(node);
+ getAssignedType(node), reference);
}
function isEmptyArrayAssignment(node) {
return node.kind === 235 /* VariableDeclaration */ && node.initializer &&
@@ -42538,6 +43368,23 @@ var ts;
}
return links.switchTypes;
}
+ // Get the types from all cases in a switch on `typeof`. An
+ // `undefined` element denotes an explicit `default` clause.
+ function getSwitchClauseTypeOfWitnesses(switchStatement) {
+ var witnesses = [];
+ for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
+ var clause = _a[_i];
+ if (clause.kind === 269 /* CaseClause */) {
+ if (clause.expression.kind === 9 /* StringLiteral */) {
+ witnesses.push(clause.expression.text);
+ continue;
+ }
+ return ts.emptyArray;
+ }
+ witnesses.push(/*explicitDefaultStatement*/ undefined);
+ }
+ return witnesses;
+ }
function eachTypeContainedIn(source, types) {
return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
}
@@ -42580,8 +43427,8 @@ var ts;
var types = type.types;
var mappedType;
var mappedTypes;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var current = types_13[_i];
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var current = types_12[_i];
var t = mapper(current);
if (t) {
if (!mappedType) {
@@ -42661,8 +43508,8 @@ var ts;
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var t = types_14[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var t = types_13[_i];
if (!(t.flags & 32768 /* Never */)) {
if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
return false;
@@ -42742,8 +43589,8 @@ var ts;
}
return resultType;
function getTypeAtFlowNode(flow) {
- if (flowDepth === 2500) {
- // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error
+ if (flowDepth === 2000) {
+ // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
// and disable further control flow analysis in the containing function or module body.
flowAnalysisDisabled = true;
reportFlowControlError(reference);
@@ -42846,11 +43693,11 @@ var ts;
if (isEmptyArrayAssignment(node)) {
return getEvolvingArrayType(neverType);
}
- var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node));
+ var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference));
return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
}
if (declaredType.flags & 262144 /* Union */) {
- return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node));
+ return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference));
}
return declaredType;
}
@@ -42882,7 +43729,8 @@ var ts;
}
}
else {
- var indexType = getTypeOfExpression(node.left.argumentExpression);
+ // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time)
+ var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) {
evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
}
@@ -42927,6 +43775,9 @@ var ts;
else if (isMatchingReferenceDiscriminant(expr, type)) {
type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
}
+ else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
+ type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
+ }
return createFlowType(type, isIncomplete(flowType));
}
function getTypeAtFlowBranchLabel(flow) {
@@ -43185,27 +44036,33 @@ var ts;
if (type.flags & 1 /* Any */ && literal.text === "function") {
return type;
}
- if (assumeTrue && !(type.flags & 262144 /* Union */)) {
- // We narrow a non-union type to an exact primitive type if the non-union type
- // is a supertype of that primitive type. For example, type 'any' can be narrowed
- // to one of the primitive types.
- var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
- if (targetType) {
- if (isTypeSubtypeOf(targetType, type)) {
- return targetType;
- }
- if (type.flags & 15794176 /* Instantiable */) {
- var constraint = getBaseConstraintOfType(type) || anyType;
- if (isTypeSubtypeOf(targetType, constraint)) {
- return getIntersectionType([type, targetType]);
- }
- }
- }
- }
var facts = assumeTrue ?
typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ :
typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */;
- return getTypeWithFacts(type, facts);
+ return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
+ function narrowTypeForTypeof(type) {
+ if (assumeTrue && !(type.flags & 262144 /* Union */)) {
+ if (type.flags & 2 /* Unknown */ && literal.text === "object") {
+ return getUnionType([nonPrimitiveType, nullType]);
+ }
+ // We narrow a non-union type to an exact primitive type if the non-union type
+ // is a supertype of that primitive type. For example, type 'any' can be narrowed
+ // to one of the primitive types.
+ var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
+ if (targetType) {
+ if (isTypeSubtypeOf(targetType, type)) {
+ return isTypeAny(type) ? targetType : getIntersectionType([type, targetType]); // Intersection to handle `string` being a subtype of `keyof T`
+ }
+ if (type.flags & 15794176 /* Instantiable */) {
+ var constraint = getBaseConstraintOfType(type) || anyType;
+ if (isTypeSubtypeOf(targetType, constraint)) {
+ return getIntersectionType([type, targetType]);
+ }
+ }
+ }
+ }
+ return type;
+ }
}
function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
// We only narrow if all case expressions specify values with unit types
@@ -43224,6 +44081,82 @@ var ts;
var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
}
+ function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
+ var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement);
+ if (!switchWitnesses.length) {
+ return type;
+ }
+ // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
+ var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
+ var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
+ var clauseWitnesses;
+ var switchFacts;
+ if (defaultCaseLocation > -1) {
+ // We no longer need the undefined denoting an
+ // explicit default case. Remove the undefined and
+ // fix-up clauseStart and clauseEnd. This means
+ // that we don't have to worry about undefined
+ // in the witness array.
+ var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
+ // The adjust clause start and end after removing the `default` statement.
+ var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
+ var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
+ clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
+ switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
+ }
+ else {
+ clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
+ switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
+ }
+ /*
+ The implied type is the raw type suggested by a
+ value being caught in this clause.
+
+ When the clause contains a default case we ignore
+ the implied type and try to narrow using any facts
+ we can learn: see `switchFacts`.
+
+ Example:
+ switch (typeof x) {
+ case 'number':
+ case 'string': break;
+ default: break;
+ case 'number':
+ case 'boolean': break
+ }
+
+ In the first clause (case `number` and `string`) the
+ implied type is number | string.
+
+ In the default clause we de not compute an implied type.
+
+ In the third clause (case `number` and `boolean`)
+ the naive implied type is number | boolean, however
+ we use the type facts to narrow the implied type to
+ boolean. We know that number cannot be selected
+ because it is caught in the first clause.
+ */
+ if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) {
+ var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts);
+ if (impliedType.flags & 262144 /* Union */) {
+ impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type);
+ }
+ if (!(impliedType.flags & 32768 /* Never */)) {
+ if (isTypeSubtypeOf(impliedType, type)) {
+ return impliedType;
+ }
+ if (type.flags & 15794176 /* Instantiable */) {
+ var constraint = getBaseConstraintOfType(type) || anyType;
+ if (isTypeSubtypeOf(impliedType, constraint)) {
+ return getIntersectionType([type, impliedType]);
+ }
+ }
+ }
+ }
+ return hasDefaultClause ?
+ filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) :
+ getTypeWithFacts(type, switchFacts);
+ }
function narrowTypeByInstanceof(type, expr, assumeTrue) {
var left = getReferenceCandidate(expr.left);
if (!isMatchingReference(reference, left)) {
@@ -43449,7 +44382,7 @@ var ts;
return type;
}
function markAliasReferenced(symbol, location) {
- if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
+ if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
markAliasSymbolAsReferenced(symbol);
}
}
@@ -44109,7 +45042,7 @@ var ts;
var args = getEffectiveCallArguments(iife);
var indexOfParameter = func.parameters.indexOf(parameter);
if (parameter.dotDotDotToken) {
- return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined);
+ return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
}
var links = getNodeLinks(iife);
var cached = links.resolvedSignature;
@@ -44225,7 +45158,7 @@ var ts;
}
// In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
function getContextualTypeForArgument(callTarget, arg) {
- var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217
+ var args = getEffectiveCallArguments(callTarget);
var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
}
@@ -44246,7 +45179,14 @@ var ts;
var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
switch (operatorToken.kind) {
case 58 /* EqualsToken */:
- return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined;
+ if (node !== right) {
+ return undefined;
+ }
+ var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
+ if (!contextSensitive) {
+ return undefined;
+ }
+ return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
case 54 /* BarBarToken */:
// When an || expression has a contextual type, the operands are contextually typed by that type. When an ||
// expression has no contextual type, the right operand is contextually typed by the type of the left operand,
@@ -44263,7 +45203,7 @@ var ts;
}
// In an assignment expression, the right operand is contextually typed by the type of the left operand.
// Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
- function isContextSensitiveAssignment(binaryExpression) {
+ function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression);
switch (kind) {
case 0 /* None */:
@@ -44282,19 +45222,46 @@ var ts;
if (!decl) {
return false;
}
- if (ts.isInJavaScriptFile(decl)) {
- return !!ts.getJSDocTypeTag(decl);
+ var lhs = binaryExpression.left;
+ var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
+ if (overallAnnotation) {
+ return getTypeFromTypeNode(overallAnnotation);
}
- else if (ts.isIdentifier(binaryExpression.left.expression)) {
- var id = binaryExpression.left.expression;
- var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true);
- return !ts.isFunctionSymbol(parentSymbol);
+ else if (ts.isIdentifier(lhs.expression)) {
+ var id = lhs.expression;
+ var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true);
+ if (parentSymbol) {
+ var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
+ if (annotated) {
+ var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText);
+ return type || false;
+ }
+ return false;
+ }
}
- return true;
+ return !ts.isInJavaScriptFile(decl);
}
- case 4 /* ThisProperty */:
case 2 /* ModuleExports */:
- return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration);
+ case 4 /* ThisProperty */:
+ if (!binaryExpression.symbol)
+ return true;
+ if (binaryExpression.symbol.valueDeclaration) {
+ var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
+ if (annotated) {
+ var type = getTypeFromTypeNode(annotated);
+ if (type) {
+ return type;
+ }
+ }
+ }
+ if (kind === 2 /* ModuleExports */)
+ return false;
+ var thisAccess = binaryExpression.left;
+ if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
+ return false;
+ }
+ var thisType = checkThisExpression(thisAccess.expression);
+ return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false;
default:
return ts.Debug.assertNever(kind);
}
@@ -44722,8 +45689,8 @@ var ts;
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var current = types_15[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var current = types_14[_i];
var signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
@@ -45261,7 +46228,7 @@ var ts;
function getJsxType(name, location) {
var namespace = getJsxNamespaceAt(location);
var exports = namespace && getExportsOfSymbol(namespace);
- var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */);
+ var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */);
return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
}
/**
@@ -45319,7 +46286,7 @@ var ts;
if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) {
candidateForTypeArgumentError = signature;
}
- var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */);
+ var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */);
var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext);
instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript));
}
@@ -45386,7 +46353,7 @@ var ts;
*/
function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
// JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
- var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */);
+ var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */);
// JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
// The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
@@ -45410,7 +46377,7 @@ var ts;
}
function getJsxLibraryManagedAttributes(jsxNamespace) {
// JSX.LibraryManagedAttributes [symbol]
- return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */);
+ return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */);
}
/// e.g. "props" for React.d.ts,
/// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
@@ -45748,7 +46715,7 @@ var ts;
var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
var reactNamespace = getJsxNamespace(node);
var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
- var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
+ var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
if (reactSym) {
// Mark local symbol as referenced here because it might not have been marked
// if jsx emit was not react as there wont be error being emitted
@@ -45917,7 +46884,7 @@ var ts;
// Referencing abstract properties within their own constructors is not allowed
if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
- if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) {
+ if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node, declaringClassDeclaration)) {
error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217
return false;
}
@@ -46185,7 +47152,7 @@ var ts;
return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
}
function getSuggestedSymbolForNonexistentProperty(name, containingType) {
- return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */);
+ return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */);
}
function getSuggestionForNonexistentProperty(name, containingType) {
var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
@@ -46356,7 +47323,7 @@ var ts;
}
return errorType;
}
- var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression);
+ var indexType = checkExpression(indexExpression);
if (objectType === errorType || objectType === silentNeverType) {
return objectType;
}
@@ -46364,7 +47331,14 @@ var ts;
error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
return errorType;
}
- return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node);
+ if (isTupleType(objectType) && !objectType.target.hasRestElement && ts.isNumericLiteral(indexExpression)) {
+ var index = +indexExpression.text;
+ var maximumIndex = ts.length(objectType.target.typeParameters);
+ if (index >= maximumIndex) {
+ error(indexExpression, ts.Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex);
+ }
+ }
+ return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node);
}
function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
if (expressionType === errorType) {
@@ -46485,16 +47459,13 @@ var ts;
}
function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
- var argCount; // Apparent number of arguments we will have in this call
- var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
- var spreadArgIndex = -1;
if (ts.isJsxOpeningLikeElement(node)) {
// The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement".
return true;
}
+ var argCount;
+ var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
if (node.kind === 191 /* TaggedTemplateExpression */) {
- // Even if the call is incomplete, we'll have a missing expression as our last argument,
- // so we can say the count is just the arg list length
argCount = args.length;
if (node.template.kind === 204 /* TemplateExpression */) {
// If a tagged template expression lacks a tail literal, the call is incomplete.
@@ -46512,7 +47483,7 @@ var ts;
}
}
else if (node.kind === 150 /* Decorator */) {
- argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature);
+ argCount = getDecoratorArgumentCount(node, signature);
}
else {
if (!node.arguments) {
@@ -46523,11 +47494,11 @@ var ts;
argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
// If we are missing the close parenthesis, the call is incomplete.
callIsIncomplete = node.arguments.end === node.end;
- spreadArgIndex = getSpreadArgumentIndex(args);
- }
- // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
- if (spreadArgIndex >= 0) {
- return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
+ // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
+ var spreadArgIndex = getSpreadArgumentIndex(args);
+ if (spreadArgIndex >= 0) {
+ return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
+ }
}
// Too many arguments implies incorrect arity.
if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) {
@@ -46558,7 +47529,7 @@ var ts;
}
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
- var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes);
+ var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
@@ -46625,58 +47596,40 @@ var ts;
var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
inferTypes(context.inferences, thisArgumentType, thisType);
}
- // We perform two passes over the arguments. In the first pass we infer from all arguments, but use
- // wildcards for all context sensitive function expressions.
- var effectiveArgCount = getEffectiveArgumentCount(node, args, signature);
- var genericRestType = getGenericRestType(signature);
- var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount;
+ var restType = getNonArrayRestType(signature);
+ var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
for (var i = 0; i < argCount; i++) {
- var arg = getEffectiveArgument(node, args, i);
- // If the effective argument is 'undefined', then it is an argument that is present but is synthetic.
- if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) {
+ var arg = args[i];
+ if (arg.kind !== 208 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = getEffectiveArgumentType(node, i);
- // If the effective argument type is 'undefined', there is no synthetic type
- // for the argument. In that case, we should check the argument.
- if (argType === undefined) {
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- argType = checkExpressionWithContextualType(arg, paramType, mapper);
- }
+ // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
+ // context sensitive function expressions as wildcards
+ var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
+ var argType = checkExpressionWithContextualType(arg, paramType, mapper);
inferTypes(context.inferences, argType, paramType);
}
}
- if (genericRestType) {
- var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context);
- inferTypes(context.inferences, spreadType, genericRestType);
- }
- // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this
- // time treating function expressions normally (which may cause previously inferred type arguments to be fixed
- // as we construct types for contextually typed parameters)
- // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed.
- // Tagged template expressions will always have `undefined` for `excludeArgument[0]`.
- if (excludeArgument) {
- for (var i = 0; i < argCount; i++) {
- // No need to check for omitted args and template expressions, their exclusion value is always undefined
- if (excludeArgument[i] === false) {
- var arg = args[i];
- var paramType = getTypeAtPosition(signature, i);
- inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType);
- }
- }
+ if (restType) {
+ var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
+ inferTypes(context.inferences, spreadType, restType);
}
return getInferredTypes(context);
}
- function getSpreadArgumentType(node, args, index, argCount, restType, context) {
+ function getArrayifiedType(type) {
+ if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) {
+ return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType);
+ }
+ return type;
+ }
+ function getSpreadArgumentType(args, index, argCount, restType, context) {
if (index >= argCount - 1) {
- var arg = getEffectiveArgument(node, args, argCount - 1);
+ var arg = args[argCount - 1];
if (isSpreadArgument(arg)) {
// We are inferring from a spread expression in the last argument position, i.e. both the parameter
// and the argument are ...x forms.
return arg.kind === 213 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- checkExpressionWithContextualType(arg.expression, restType, context);
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -46684,12 +47637,9 @@ var ts;
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = getEffectiveArgumentType(node, i);
- if (!argType) {
- argType = checkExpressionWithContextualType(args[i], contextualType, context);
- if (spreadIndex < 0 && isSpreadArgument(args[i])) {
- spreadIndex = i - index;
- }
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ if (spreadIndex < 0 && isSpreadArgument(args[i])) {
+ spreadIndex = i - index;
}
types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
}
@@ -46705,16 +47655,16 @@ var ts;
for (var i = 0; i < typeArgumentNodes.length; i++) {
ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
var constraint = getConstraintOfTypeParameter(typeParameters[i]);
- if (!constraint)
- continue;
- var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
- var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
- if (!mapper) {
- mapper = createTypeMapper(typeParameters, typeArgumentTypes);
- }
- var typeArgument = typeArgumentTypes[i];
- if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
- return false;
+ if (constraint) {
+ var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
+ var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
+ if (!mapper) {
+ mapper = createTypeMapper(typeParameters, typeArgumentTypes);
+ }
+ var typeArgument = typeArgumentTypes[i];
+ if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
+ return undefined;
+ }
}
}
return typeArgumentTypes;
@@ -46769,36 +47719,27 @@ var ts;
}
}
var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
- var argCount = getEffectiveArgumentCount(node, args, signature);
- var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1;
- var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType;
+ var restType = getNonArrayRestType(signature);
+ var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
for (var i = 0; i < argCount; i++) {
- var arg = getEffectiveArgument(node, args, i);
- // If the effective argument is 'undefined', then it is an argument that is present but is synthetic.
- if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) {
- if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) {
- var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined);
- return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage);
- }
- else {
- // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter)
- var paramType = getTypeAtPosition(signature, i);
- // If the effective argument type is undefined, there is no synthetic type for the argument.
- // In that case, we should check the argument.
- var argType = getEffectiveArgumentType(node, i) ||
- checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
- // we obtain the regular type of any object literal arguments because we may not have inferred complete
- // parameter types yet and therefore excess property checks may yield false positives (see #17041).
- var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
- // Use argument expression as error location when reporting errors
- var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined;
- if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) {
- return false;
- }
+ var arg = args[i];
+ if (arg.kind !== 208 /* OmittedExpression */) {
+ var paramType = getTypeAtPosition(signature, i);
+ var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
+ // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ // we obtain the regular type of any object literal arguments because we may not have inferred complete
+ // parameter types yet and therefore excess property checks may yield false positives (see #17041).
+ var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
+ if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
+ return false;
}
}
}
+ if (restType) {
+ var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
+ var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
+ return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage);
+ }
return true;
}
/**
@@ -46812,303 +47753,108 @@ var ts;
}
}
}
+ function createSyntheticExpression(parent, type, isSpread) {
+ var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end);
+ result.parent = parent;
+ result.type = type;
+ result.isSpread = isSpread || false;
+ return result;
+ }
/**
* Returns the effective arguments for an expression that works like a function invocation.
- *
- * If 'node' is a CallExpression or a NewExpression, then its argument list is returned.
- * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution
- * expressions, where the first element of the list is `undefined`.
- * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types
- * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`.
*/
function getEffectiveCallArguments(node) {
if (node.kind === 191 /* TaggedTemplateExpression */) {
var template = node.template;
- var args_4 = [undefined]; // TODO: GH#18217
+ var args_5 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
if (template.kind === 204 /* TemplateExpression */) {
ts.forEach(template.templateSpans, function (span) {
- args_4.push(span.expression);
+ args_5.push(span.expression);
});
}
- return args_4;
+ return args_5;
}
- else if (node.kind === 150 /* Decorator */) {
- // For a decorator, we return undefined as we will determine
- // the number and types of arguments for a decorator using
- // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below.
- return undefined;
+ if (node.kind === 150 /* Decorator */) {
+ return getEffectiveDecoratorArguments(node);
}
- else if (ts.isJsxOpeningLikeElement(node)) {
+ if (ts.isJsxOpeningLikeElement(node)) {
return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray;
}
- else {
- var args = node.arguments || ts.emptyArray;
- var length_4 = args.length;
- if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) {
- // We have a spread argument in the last position and no other spread arguments. If the type
- // of the argument is a tuple type, spread the tuple elements into the argument list. We can
- // call checkExpressionCached because spread expressions never have a contextual type.
- var spreadArgument_1 = args[length_4 - 1];
- var type = checkExpressionCached(spreadArgument_1.expression);
- if (isTupleType(type)) {
- var typeArguments = type.typeArguments || ts.emptyArray;
- var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
- var syntheticArgs = ts.map(typeArguments, function (t, i) {
- var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end);
- arg.parent = spreadArgument_1;
- arg.type = t;
- arg.isSpread = i === restIndex_2;
- return arg;
- });
- return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs);
- }
- }
- return args;
- }
- }
- /**
- * Returns the effective argument count for a node that works like a function invocation.
- * If 'node' is a Decorator, the number of arguments is derived from the decoration
- * target and the signature:
- * If 'node.target' is a class declaration or class expression, the effective argument
- * count is 1.
- * If 'node.target' is a parameter declaration, the effective argument count is 3.
- * If 'node.target' is a property declaration, the effective argument count is 2.
- * If 'node.target' is a method or accessor declaration, the effective argument count
- * is 3, although it can be 2 if the signature only accepts two arguments, allowing
- * us to match a property decorator.
- * Otherwise, the argument count is the length of the 'args' array.
- */
- function getEffectiveArgumentCount(node, args, signature) {
- if (node.kind === 150 /* Decorator */) {
- switch (node.parent.kind) {
- case 238 /* ClassDeclaration */:
- case 207 /* ClassExpression */:
- // A class decorator will have one argument (see `ClassDecorator` in core.d.ts)
- return 1;
- case 152 /* PropertyDeclaration */:
- // A property declaration decorator will have two arguments (see
- // `PropertyDecorator` in core.d.ts)
- return 2;
- case 154 /* MethodDeclaration */:
- case 156 /* GetAccessor */:
- case 157 /* SetAccessor */:
- // A method or accessor declaration decorator will have two or three arguments (see
- // `PropertyDecorator` and `MethodDecorator` in core.d.ts)
- // If we are emitting decorators for ES3, we will only pass two arguments.
- if (languageVersion === 0 /* ES3 */) {
- return 2;
- }
- // If the method decorator signature only accepts a target and a key, we will only
- // type check those arguments.
- return signature.parameters.length >= 3 ? 3 : 2;
- case 149 /* Parameter */:
- // A parameter declaration decorator will have three arguments (see
- // `ParameterDecorator` in core.d.ts)
- return 3;
- default:
- return ts.Debug.fail();
+ var args = node.arguments || ts.emptyArray;
+ var length = args.length;
+ if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
+ // We have a spread argument in the last position and no other spread arguments. If the type
+ // of the argument is a tuple type, spread the tuple elements into the argument list. We can
+ // call checkExpressionCached because spread expressions never have a contextual type.
+ var spreadArgument_1 = args[length - 1];
+ var type = checkExpressionCached(spreadArgument_1.expression);
+ if (isTupleType(type)) {
+ var typeArguments = type.typeArguments || ts.emptyArray;
+ var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
+ var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
+ return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
}
}
- else {
- return args.length;
- }
+ return args;
}
/**
- * Returns the effective type of the first argument to a decorator.
- * If 'node' is a class declaration or class expression, the effective argument type
- * is the type of the static side of the class.
- * If 'node' is a parameter declaration, the effective argument type is either the type
- * of the static or instance side of the class for the parameter's parent method,
- * depending on whether the method is declared static.
- * For a constructor, the type is always the type of the static side of the class.
- * If 'node' is a property, method, or accessor declaration, the effective argument
- * type is the type of the static or instance side of the parent class for class
- * element, depending on whether the element is declared static.
+ * Returns the synthetic argument list for a decorator invocation.
*/
- function getEffectiveDecoratorFirstArgumentType(node) {
- // The first argument to a decorator is its `target`.
- if (node.kind === 238 /* ClassDeclaration */) {
- // For a class decorator, the `target` is the type of the class (e.g. the
- // "static" or "constructor" side of the class)
- var classSymbol = getSymbolOfNode(node);
- return getTypeOfSymbol(classSymbol);
+ function getEffectiveDecoratorArguments(node) {
+ var parent = node.parent;
+ var expr = node.expression;
+ switch (parent.kind) {
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ // For a class decorator, the `target` is the type of the class (e.g. the
+ // "static" or "constructor" side of the class).
+ return [
+ createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
+ ];
+ case 149 /* Parameter */:
+ // A parameter declaration decorator will have three arguments (see
+ // `ParameterDecorator` in core.d.ts).
+ var func = parent.parent;
+ return [
+ createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
+ createSyntheticExpression(expr, anyType),
+ createSyntheticExpression(expr, numberType)
+ ];
+ case 152 /* PropertyDeclaration */:
+ case 154 /* MethodDeclaration */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ // A method or accessor declaration decorator will have two or three arguments (see
+ // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
+ // for ES3, we will only pass two arguments.
+ var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
+ return [
+ createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
+ createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
+ createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
+ ];
}
- if (node.kind === 149 /* Parameter */) {
- // For a parameter decorator, the `target` is the parent type of the
- // parameter's containing method.
- node = node.parent;
- if (node.kind === 155 /* Constructor */) {
- var classSymbol = getSymbolOfNode(node);
- return getTypeOfSymbol(classSymbol);
- }
- }
- if (node.kind === 152 /* PropertyDeclaration */ ||
- node.kind === 154 /* MethodDeclaration */ ||
- node.kind === 156 /* GetAccessor */ ||
- node.kind === 157 /* SetAccessor */) {
- // For a property or method decorator, the `target` is the
- // "static"-side type of the parent of the member if the member is
- // declared "static"; otherwise, it is the "instance"-side type of the
- // parent of the member.
- return getParentTypeOfClassElement(node);
- }
- ts.Debug.fail("Unsupported decorator target.");
- return errorType;
+ return ts.Debug.fail();
}
/**
- * Returns the effective type for the second argument to a decorator.
- * If 'node' is a parameter, its effective argument type is one of the following:
- * If 'node.parent' is a constructor, the effective argument type is 'any', as we
- * will emit `undefined`.
- * If 'node.parent' is a member with an identifier, numeric, or string literal name,
- * the effective argument type will be a string literal type for the member name.
- * If 'node.parent' is a computed property name, the effective argument type will
- * either be a symbol type or the string type.
- * If 'node' is a member with an identifier, numeric, or string literal name, the
- * effective argument type will be a string literal type for the member name.
- * If 'node' is a computed property name, the effective argument type will either
- * be a symbol type or the string type.
- * A class decorator does not have a second argument type.
+ * Returns the argument count for a decorator node that works like a function invocation.
*/
- function getEffectiveDecoratorSecondArgumentType(node) {
- // The second argument to a decorator is its `propertyKey`
- if (node.kind === 238 /* ClassDeclaration */) {
- ts.Debug.fail("Class decorators should not have a second synthetic argument.");
- return errorType;
- }
- if (node.kind === 149 /* Parameter */) {
- node = node.parent;
- if (node.kind === 155 /* Constructor */) {
- // For a constructor parameter decorator, the `propertyKey` will be `undefined`.
- return anyType;
- }
- // For a non-constructor parameter decorator, the `propertyKey` will be either
- // a string or a symbol, based on the name of the parameter's containing method.
- }
- if (node.kind === 152 /* PropertyDeclaration */ ||
- node.kind === 154 /* MethodDeclaration */ ||
- node.kind === 156 /* GetAccessor */ ||
- node.kind === 157 /* SetAccessor */) {
- // The `propertyKey` for a property or method decorator will be a
- // string literal type if the member name is an identifier, number, or string;
- // otherwise, if the member name is a computed property name it will
- // be either string or symbol.
- var element = node;
- var name = element.name;
- switch (name.kind) {
- case 71 /* Identifier */:
- return getLiteralType(ts.idText(name));
- case 8 /* NumericLiteral */:
- case 9 /* StringLiteral */:
- return getLiteralType(name.text);
- case 147 /* ComputedPropertyName */:
- var nameType = checkComputedPropertyName(name);
- if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) {
- return nameType;
- }
- else {
- return stringType;
- }
- default:
- ts.Debug.fail("Unsupported property name.");
- return errorType;
- }
- }
- ts.Debug.fail("Unsupported decorator target.");
- return errorType;
- }
- /**
- * Returns the effective argument type for the third argument to a decorator.
- * If 'node' is a parameter, the effective argument type is the number type.
- * If 'node' is a method or accessor, the effective argument type is a
- * `TypedPropertyDescriptor` instantiated with the type of the member.
- * Class and property decorators do not have a third effective argument.
- */
- function getEffectiveDecoratorThirdArgumentType(node) {
- // The third argument to a decorator is either its `descriptor` for a method decorator
- // or its `parameterIndex` for a parameter decorator
- if (node.kind === 238 /* ClassDeclaration */) {
- ts.Debug.fail("Class decorators should not have a third synthetic argument.");
- return errorType;
- }
- if (node.kind === 149 /* Parameter */) {
- // The `parameterIndex` for a parameter decorator is always a number
- return numberType;
- }
- if (node.kind === 152 /* PropertyDeclaration */) {
- ts.Debug.fail("Property decorators should not have a third synthetic argument.");
- return errorType;
- }
- if (node.kind === 154 /* MethodDeclaration */ ||
- node.kind === 156 /* GetAccessor */ ||
- node.kind === 157 /* SetAccessor */) {
- // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor`
- // for the type of the member.
- var propertyType = getTypeOfNode(node);
- return createTypedPropertyDescriptorType(propertyType);
- }
- ts.Debug.fail("Unsupported decorator target.");
- return errorType;
- }
- /**
- * Returns the effective argument type for the provided argument to a decorator.
- */
- function getEffectiveDecoratorArgumentType(node, argIndex) {
- if (argIndex === 0) {
- return getEffectiveDecoratorFirstArgumentType(node.parent);
- }
- else if (argIndex === 1) {
- return getEffectiveDecoratorSecondArgumentType(node.parent);
- }
- else if (argIndex === 2) {
- return getEffectiveDecoratorThirdArgumentType(node.parent);
- }
- ts.Debug.fail("Decorators should not have a fourth synthetic argument.");
- return errorType;
- }
- /**
- * Gets the effective argument type for an argument in a call expression.
- */
- function getEffectiveArgumentType(node, argIndex) {
- // Decorators provide special arguments, a tagged template expression provides
- // a special first argument, and string literals get string literal types
- // unless we're reporting errors
- if (node.kind === 150 /* Decorator */) {
- return getEffectiveDecoratorArgumentType(node, argIndex);
- }
- else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) {
- return getGlobalTemplateStringsArrayType();
- }
- // This is not a synthetic argument, so we return 'undefined'
- // to signal that the caller needs to check the argument.
- return undefined;
- }
- /**
- * Gets the effective argument expression for an argument in a call expression.
- */
- function getEffectiveArgument(node, args, argIndex) {
- // For a decorator or the first argument of a tagged template expression we return undefined.
- if (node.kind === 150 /* Decorator */ ||
- (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) {
- return undefined;
- }
- return args[argIndex];
- }
- /**
- * Gets the error node to use when reporting errors for an effective argument.
- */
- function getEffectiveArgumentErrorNode(node, argIndex, arg) {
- if (node.kind === 150 /* Decorator */) {
- // For a decorator, we use the expression of the decorator for error reporting.
- return node.expression;
- }
- else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) {
- // For a the first argument of a tagged template expression, we use the template of the tag for error reporting.
- return node.template;
- }
- else {
- return arg;
+ function getDecoratorArgumentCount(node, signature) {
+ switch (node.parent.kind) {
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ return 1;
+ case 152 /* PropertyDeclaration */:
+ return 2;
+ case 154 /* MethodDeclaration */:
+ case 156 /* GetAccessor */:
+ case 157 /* SetAccessor */:
+ // For ES3 or decorators with only two parameters we supply only two arguments
+ return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
+ case 149 /* Parameter */:
+ return 3;
+ default:
+ return ts.Debug.fail();
}
}
function getArgumentArityError(node, signatures, args) {
@@ -47117,6 +47863,7 @@ var ts;
var belowArgCount = Number.NEGATIVE_INFINITY;
var aboveArgCount = Number.POSITIVE_INFINITY;
var argCount = args.length;
+ var closestSignature;
for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) {
var sig = signatures_5[_i];
var minCount = getMinArgumentCount(sig);
@@ -47125,7 +47872,10 @@ var ts;
belowArgCount = minCount;
if (argCount < maxCount && maxCount < aboveArgCount)
aboveArgCount = maxCount;
- min = Math.min(min, minCount);
+ if (minCount < min) {
+ min = minCount;
+ closestSignature = sig;
+ }
max = Math.max(max, maxCount);
}
var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
@@ -47136,16 +47886,25 @@ var ts;
if (argCount <= max && hasSpreadArgument) {
argCount--;
}
+ var related;
+ if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
+ var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
+ if (paramDecl) {
+ related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
+ }
+ }
if (hasRestParameter || hasSpreadArgument) {
var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
ts.Diagnostics.Expected_0_arguments_but_got_1_or_more;
- return ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
+ var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
+ return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1;
}
if (min < argCount && argCount < max) {
return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
}
- return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
+ var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
+ return related ? addRelatedInfo(diagnostic, related) : diagnostic;
}
function getTypeArgumentArityError(node, signatures, typeArguments) {
var min = Infinity;
@@ -47178,36 +47937,20 @@ var ts;
return resolveErrorCall(node);
}
var args = getEffectiveCallArguments(node);
- // The following applies to any value of 'excludeArgument[i]':
- // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing.
- // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing.
- // - false: the argument at 'i' *was* and *has been* permanently contextually typed.
+ // The excludeArgument array contains true for each context sensitive argument (an argument
+ // is context sensitive it is susceptible to a one-time permanent contextual typing).
//
// The idea is that we will perform type argument inference & assignability checking once
- // without using the susceptible parameters that are functions, and once more for each of those
+ // without using the susceptible parameters that are functions, and once more for those
// parameters, contextually typing each as we go along.
//
- // For a tagged template, then the first argument be 'undefined' if necessary
- // because it represents a TemplateStringsArray.
+ // For a tagged template, then the first argument be 'undefined' if necessary because it
+ // represents a TemplateStringsArray.
//
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument;
- var excludeCount = 0;
- if (!isDecorator && !isSingleNonGenericCandidate) {
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- excludeCount++;
- }
- }
- }
+ var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -47277,14 +48020,17 @@ var ts;
else if (candidateForTypeArgumentError) {
checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
}
- else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) {
- diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
- }
- else if (args) {
- diagnostics.add(getArgumentArityError(node, signatures, args));
- }
- else if (fallbackError) {
- diagnostics.add(ts.createDiagnosticForNode(node, fallbackError));
+ else {
+ var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
+ if (signaturesWithCorrectTypeArgumentArity.length === 0) {
+ diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
+ }
+ else if (!isDecorator) {
+ diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
+ }
+ else if (fallbackError) {
+ diagnostics.add(ts.createDiagnosticForNode(node, fallbackError));
+ }
}
return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
@@ -47304,60 +48050,74 @@ var ts;
return candidate;
}
for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
- var originalCandidate = candidates[candidateIndex];
- if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) {
+ var candidate = candidates[candidateIndex];
+ if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
continue;
}
- var candidate = void 0;
- var inferenceContext = originalCandidate.typeParameters ?
- createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) :
- undefined;
- while (true) {
- candidate = originalCandidate;
- if (candidate.typeParameters) {
- var typeArgumentTypes = void 0;
- if (typeArguments) {
- var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
- if (typeArgumentResult) {
- typeArgumentTypes = typeArgumentResult;
- }
- else {
- candidateForTypeArgumentError = originalCandidate;
- break;
- }
+ var checkCandidate = void 0;
+ var inferenceContext = void 0;
+ if (candidate.typeParameters) {
+ var typeArgumentTypes = void 0;
+ if (typeArguments) {
+ typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
+ if (!typeArgumentTypes) {
+ candidateForTypeArgumentError = candidate;
+ continue;
}
- else {
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- }
- var isJavascript = ts.isInJavaScriptFile(candidate.declaration);
- candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript);
- // If the original signature has a generic rest type, instantiation may produce a
- // signature with different arity and we need to perform another arity check.
- if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
- candidateForArgumentArityError = candidate;
- break;
- }
- }
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
- candidateForArgumentError = candidate;
- break;
- }
- if (excludeCount === 0) {
- candidates[candidateIndex] = candidate;
- return candidate;
- }
- excludeCount--;
- if (excludeCount > 0) {
- excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false;
}
else {
- excludeArgument = undefined;
+ inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJavaScriptFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ }
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJavaScriptFile(candidate.declaration));
+ // If the original signature has a generic rest type, instantiation may produce a
+ // signature with different arity and we need to perform another arity check.
+ if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
+ candidateForArgumentArityError = checkCandidate;
+ continue;
}
}
+ else {
+ checkCandidate = candidate;
+ }
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ candidateForArgumentError = checkCandidate;
+ continue;
+ }
+ if (excludeArgument) {
+ // If one or more context sensitive arguments were excluded, we start including
+ // them now (and keeping do so for any subsequent candidates) and perform a second
+ // round of type inference and applicability checking for this particular candidate.
+ excludeArgument = undefined;
+ if (inferenceContext) {
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJavaScriptFile(candidate.declaration));
+ }
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ candidateForArgumentError = checkCandidate;
+ continue;
+ }
+ }
+ candidates[candidateIndex] = checkCandidate;
+ return checkCandidate;
}
return undefined;
}
}
+ function getExcludeArgument(args) {
+ var excludeArgument;
+ // We do not need to call `getEffectiveArgumentCount` here as it only
+ // applies when calculating the number of arguments for a decorator.
+ for (var i = 0; i < args.length; i++) {
+ if (isContextSensitive(args[i])) {
+ if (!excludeArgument) {
+ excludeArgument = new Array(args.length);
+ }
+ excludeArgument[i] = true;
+ }
+ }
+ return excludeArgument;
+ }
// No signature was applicable. We have already reported the errors for the invalid signature.
// If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
@@ -47427,17 +48187,27 @@ var ts;
if (!typeParameters) {
return candidate;
}
- var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray;
+ var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
+ var instantiated = typeArgumentNodes
+ ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJavaScriptFile(node)))
+ : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
+ candidates[bestIndex] = instantiated;
+ return instantiated;
+ }
+ function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
var typeArguments = typeArgumentNodes.map(getTypeOfNode);
while (typeArguments.length > typeParameters.length) {
typeArguments.pop();
}
while (typeArguments.length < typeParameters.length) {
- typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node)));
+ typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
}
- var instantiated = createSignatureInstantiation(candidate, typeArguments);
- candidates[bestIndex] = instantiated;
- return instantiated;
+ return typeArguments;
+ }
+ function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
+ var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJavaScriptFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
var maxParamsIndex = -1;
@@ -47588,11 +48358,13 @@ var ts;
var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
if (callSignatures.length) {
var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
- if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
- error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
- }
- if (getThisTypeOfSignature(signature) === voidType) {
- error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
+ if (!noImplicitAny) {
+ if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
+ error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
+ }
+ if (getThisTypeOfSignature(signature) === voidType) {
+ error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
+ }
}
return signature;
}
@@ -47758,7 +48530,7 @@ var ts;
return signatures.length && ts.every(signatures, function (signature) {
return signature.minArgumentCount === 0 &&
!signature.hasRestParameter &&
- signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature);
+ signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
/**
@@ -47985,7 +48757,7 @@ var ts;
if (!globalESSymbol) {
return false;
}
- return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
+ return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
}
function checkImportCallExpression(node) {
// Check grammar of dynamic import
@@ -48044,7 +48816,7 @@ var ts;
// Make sure require is not a local function
if (!ts.isIdentifier(node.expression))
return ts.Debug.fail();
- var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
+ var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
if (resolvedRequire === requireSymbol) {
return true;
}
@@ -48169,14 +48941,11 @@ var ts;
}
function getRestTypeAtPosition(source, pos) {
var paramCount = getParameterCount(source);
- var hasRest = hasEffectiveRestParameter(source);
- if (hasRest && pos === paramCount - 1) {
- var genericRestType = getGenericRestType(source);
- if (genericRestType) {
- return genericRestType;
- }
+ var restType = getEffectiveRestType(source);
+ if (restType && pos === paramCount - 1) {
+ return restType;
}
- var start = hasRest ? Math.min(pos, paramCount - 1) : pos;
+ var start = restType ? Math.min(pos, paramCount - 1) : pos;
var types = [];
var names = [];
for (var i = start; i < paramCount; i++) {
@@ -48185,17 +48954,7 @@ var ts;
}
var minArgumentCount = getMinArgumentCount(source);
var minLength = minArgumentCount < start ? 0 : minArgumentCount - start;
- return createTupleType(types, minLength, hasRest, names);
- }
- function getTypeOfRestParameter(signature) {
- if (signature.hasRestParameter) {
- var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
- if (isTupleType(restType)) {
- return getRestTypeOfTupleType(restType);
- }
- return restType;
- }
- return undefined;
+ return createTupleType(types, minLength, !!restType, names);
}
function getParameterCount(signature) {
var length = signature.parameters.length;
@@ -48219,15 +48978,6 @@ var ts;
}
return signature.minArgumentCount;
}
- function getGenericRestType(signature) {
- if (signature.hasRestParameter) {
- var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
- if (restType.flags & 15794176 /* Instantiable */) {
- return restType;
- }
- }
- return undefined;
- }
function hasEffectiveRestParameter(signature) {
if (signature.hasRestParameter) {
var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
@@ -48235,6 +48985,17 @@ var ts;
}
return false;
}
+ function getEffectiveRestType(signature) {
+ if (signature.hasRestParameter) {
+ var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
+ return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
+ }
+ return undefined;
+ }
+ function getNonArrayRestType(signature) {
+ var restType = getEffectiveRestType(signature);
+ return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined;
+ }
function getTypeOfFirstParameterOfSignature(signature) {
return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
}
@@ -48437,10 +49198,61 @@ var ts;
? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
: ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
+ /**
+ * Collect the TypeFacts learned from a typeof switch with
+ * total clauses `witnesses`, and the active clause ranging
+ * from `start` to `end`. Parameter `hasDefault` denotes
+ * whether the active clause contains a default clause.
+ */
+ function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
+ var facts = 0 /* None */;
+ // When in the default we only collect inequality facts
+ // because default is 'in theory' a set of infinite
+ // equalities.
+ if (hasDefault) {
+ // Value is not equal to any types after the active clause.
+ for (var i = end; i < witnesses.length; i++) {
+ facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */;
+ }
+ // Remove inequalities for types that appear in the
+ // active clause because they appear before other
+ // types collected so far.
+ for (var i = start; i < end; i++) {
+ facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
+ }
+ // Add inequalities for types before the active clause unconditionally.
+ for (var i = 0; i < start; i++) {
+ facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */;
+ }
+ }
+ // When in an active clause without default the set of
+ // equalities is finite.
+ else {
+ // Add equalities for all types in the active clause.
+ for (var i = start; i < end; i++) {
+ facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */;
+ }
+ // Remove equalities for types that appear before the
+ // active clause.
+ for (var i = 0; i < start; i++) {
+ facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
+ }
+ }
+ return facts;
+ }
function isExhaustiveSwitchStatement(node) {
if (!node.possiblyExhaustive) {
return false;
}
+ if (node.expression.kind === 197 /* TypeOfExpression */) {
+ var operandType = getTypeOfExpression(node.expression.expression);
+ // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined.
+ var witnesses = getSwitchClauseTypeOfWitnesses(node);
+ // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
+ var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
+ var type_4 = getBaseConstraintOfType(operandType) || operandType;
+ return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */);
+ }
var type = getTypeOfExpression(node.expression);
if (!isLiteralType(type)) {
return false;
@@ -48569,8 +49381,10 @@ var ts;
return links_1.contextFreeType;
}
var returnType = getReturnTypeFromBody(node, checkMode);
- var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
- return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined);
+ var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
+ var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
+ returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ return links_1.contextFreeType = returnOnlyType;
}
return anyFunctionType;
}
@@ -48816,8 +49630,8 @@ var ts;
}
if (type.flags & 786432 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var t = types_16[_i];
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var t = types_15[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -49281,7 +50095,7 @@ var ts;
var propType = getTypeOfSymbol(prop);
if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
var name = prop.escapedName;
- var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false);
+ var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false);
if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name));
return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name));
@@ -49492,7 +50306,7 @@ var ts;
var initializer = ts.getEffectiveInitializer(declaration);
var type = getTypeOfExpression(initializer, /*cache*/ true);
var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ ||
- (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) ||
+ ts.isDeclarationReadonly(declaration) ||
isTypeAssertion(initializer) ? type : getWidenedLiteralType(type);
if (ts.isInJavaScriptFile(declaration)) {
if (widened.flags & 24576 /* Nullable */) {
@@ -49586,15 +50400,19 @@ var ts;
* to cache the result.
*/
function getTypeOfExpression(node, cache) {
+ var expr = ts.skipParentheses(node);
// Optimize for the common case of a call to a function with a single non-generic call
// signature where we can just fetch the return type without checking the arguments.
- if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) {
- var funcType = checkNonNullExpression(node.expression);
+ if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
+ var funcType = checkNonNullExpression(expr.expression);
var signature = getSingleCallSignature(funcType);
if (signature && !signature.typeParameters) {
return getReturnTypeOfSignature(signature);
}
}
+ else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) {
+ return getTypeFromTypeNode(expr.type);
+ }
// Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
// should have a parameter that indicates whether full error checking is required such that
// we can perform the optimizations locally.
@@ -49608,9 +50426,13 @@ var ts;
* It sets the contextual type of the node to any before calling getTypeOfExpression.
*/
function getContextFreeTypeOfExpression(node) {
+ var links = getNodeLinks(node);
+ if (links.contextFreeType) {
+ return links.contextFreeType;
+ }
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = getTypeOfExpression(node);
+ var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
@@ -49770,9 +50592,6 @@ var ts;
checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
}
}
- function isRestParameterType(type) {
- return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType);
- }
function checkParameter(node) {
// Grammar checking
// It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
@@ -49802,7 +50621,7 @@ var ts;
}
// Only check rest parameter type if it's not a binding pattern. Since binding patterns are
// not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
- if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) {
+ if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) {
error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
}
}
@@ -50640,6 +51459,13 @@ var ts;
}
}
}
+ var DeclarationSpaces;
+ (function (DeclarationSpaces) {
+ DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
+ DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
+ DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
+ DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
+ })(DeclarationSpaces || (DeclarationSpaces = {}));
function checkExportsOnMergedDeclarations(node) {
if (!produceDiagnostics) {
return;
@@ -50697,13 +51523,6 @@ var ts;
}
}
}
- var DeclarationSpaces;
- (function (DeclarationSpaces) {
- DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
- DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
- DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
- DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
- })(DeclarationSpaces || (DeclarationSpaces = {}));
function getDeclarationSpaces(decl) {
var d = decl;
switch (d.kind) {
@@ -50733,10 +51552,10 @@ var ts;
case 246 /* ImportEqualsDeclaration */:
case 249 /* NamespaceImport */:
case 248 /* ImportClause */:
- var result_3 = 0 /* None */;
+ var result_4 = 0 /* None */;
var target = resolveAlias(getSymbolOfNode(d));
- ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); });
- return result_3;
+ ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); });
+ return result_4;
case 235 /* VariableDeclaration */:
case 184 /* BindingElement */:
case 237 /* FunctionDeclaration */:
@@ -50966,7 +51785,7 @@ var ts;
error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType));
return;
}
- var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true);
+ var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true);
var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
if (promiseConstructorType === errorType) {
if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
@@ -50989,7 +51808,7 @@ var ts;
}
// Verify there is no local declaration that could collide with the promise constructor.
var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName);
- var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */);
+ var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */);
if (collidingSymbol) {
error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
return;
@@ -51046,7 +51865,7 @@ var ts;
if (!typeName)
return;
var rootName = getFirstIdentifier(typeName);
- var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
+ var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
if (rootSymbol
&& rootSymbol.flags & 2097152 /* Alias */
@@ -51801,7 +52620,7 @@ var ts;
else if (n.kind === 71 /* Identifier */) {
// check FunctionLikeDeclaration.locals (stores parameters\function local variable)
// if it contains entry with a specified name
- var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
+ var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) {
return;
}
@@ -51884,7 +52703,7 @@ var ts;
if (nameText) {
var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217
markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
- if (parent.initializer && property && !ts.isComputedPropertyName(name)) {
+ if (parent.initializer && property) {
checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property);
}
}
@@ -53616,8 +54435,8 @@ var ts;
// Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
// otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
// in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
- var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) |
- (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) |
+ var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) |
+ (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) |
(symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
if (target.flags & excludedMeanings) {
var message = node.kind === 255 /* ExportSpecifier */ ?
@@ -53628,7 +54447,7 @@ var ts;
// Don't allow to re-export something with no value side when `--isolatedModules` is set.
if (compilerOptions.isolatedModules
&& node.kind === 255 /* ExportSpecifier */
- && !(target.flags & 67216319 /* Value */)
+ && !(target.flags & 67220415 /* Value */)
&& !(node.flags & 4194304 /* Ambient */)) {
error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided);
}
@@ -53681,14 +54500,14 @@ var ts;
if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) {
var target = resolveAlias(getSymbolOfNode(node));
if (target !== unknownSymbol) {
- if (target.flags & 67216319 /* Value */) {
+ if (target.flags & 67220415 /* Value */) {
// Target is a value symbol, check that it is not hidden by a local declaration with the same name
var moduleName = getFirstIdentifier(node.moduleReference);
- if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
+ if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
}
}
- if (target.flags & 67901928 /* Type */) {
+ if (target.flags & 67897832 /* Type */) {
checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
}
}
@@ -53742,13 +54561,13 @@ var ts;
}
function checkExportSpecifier(node) {
checkAliasSymbol(node);
- if (compilerOptions.declaration) {
+ if (ts.getEmitDeclarations(compilerOptions)) {
collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
}
if (!node.parent.parent.moduleSpecifier) {
var exportedName = node.propertyName || node.name;
// find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
- var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
+ var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
/*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
@@ -53779,7 +54598,7 @@ var ts;
}
if (node.expression.kind === 71 /* Identifier */) {
markExportAsReferenced(node);
- if (compilerOptions.declaration) {
+ if (ts.getEmitDeclarations(compilerOptions)) {
collectLinkedAliases(node.expression, /*setVisibility*/ true);
}
}
@@ -54273,7 +55092,7 @@ var ts;
// (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
// Note: that the memberFlags come from previous iteration.
if (!isStatic) {
- copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */);
+ copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */);
}
break;
case 194 /* FunctionExpression */:
@@ -54358,9 +55177,9 @@ var ts;
}
return result;
}
- function isNodeWithinConstructorOfClass(node, classDeclaration) {
- return ts.findAncestor(node, function (element) {
- if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) {
+ function isNodeUsedDuringClassInitialization(node, classDeclaration) {
+ return !!ts.findAncestor(node, function (element) {
+ if ((ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) && element.parent === classDeclaration) {
return true;
}
else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) {
@@ -54426,7 +55245,7 @@ var ts;
if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) {
// Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
var success = resolveEntityName(entityName,
- /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
+ /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
if (success && success !== unknownSymbol) {
return success;
}
@@ -54452,10 +55271,10 @@ var ts;
var meaning = 0 /* None */;
// In an interface or class, we're definitely interested in a type.
if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) {
- meaning = 67901928 /* Type */;
+ meaning = 67897832 /* Type */;
// In a class 'extends' clause we are also looking for a value.
if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) {
- meaning |= 67216319 /* Value */;
+ meaning |= 67220415 /* Value */;
}
}
else {
@@ -54485,7 +55304,7 @@ var ts;
var symbol = getIntrinsicTagSymbol(entityName.parent);
return symbol === unknownSymbol ? undefined : symbol;
}
- return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
+ return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
}
else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) {
var links = getNodeLinks(entityName);
@@ -54502,7 +55321,7 @@ var ts;
}
}
else if (isTypeReferenceIdentifier(entityName)) {
- var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */;
+ var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */;
return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
}
else if (entityName.parent.kind === 265 /* JsxAttribute */) {
@@ -54597,6 +55416,7 @@ var ts;
case 79 /* DefaultKeyword */:
case 89 /* FunctionKeyword */:
case 36 /* EqualsGreaterThanToken */:
+ case 75 /* ClassKeyword */:
return getSymbolOfNode(node.parent);
case 181 /* ImportType */:
return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined;
@@ -54606,7 +55426,7 @@ var ts;
}
function getShorthandAssignmentValueSymbol(location) {
if (location && location.kind === 274 /* ShorthandPropertyAssignment */) {
- return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */);
+ return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */);
}
return undefined;
}
@@ -54614,7 +55434,7 @@ var ts;
function getExportSpecifierLocalTargetSymbol(node) {
return node.parent.parent.moduleSpecifier ?
getExternalModuleMember(node.parent.parent, node) :
- resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
+ resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
}
function getTypeOfNode(node) {
if (node.flags & 8388608 /* InWithStatement */) {
@@ -54624,9 +55444,7 @@ var ts;
if (ts.isPartOfTypeNode(node)) {
var typeFromTypeNode = getTypeFromTypeNode(node);
if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) {
- var containingClass = ts.getContainingClass(node);
- var classType = getTypeOfNode(containingClass);
- typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType);
+ return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType);
}
return typeFromTypeNode;
}
@@ -54636,8 +55454,7 @@ var ts;
if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) {
// A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
// extends clause of a class. We handle that case here.
- var classNode = ts.getContainingClass(node);
- var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode));
+ var classType = getTypeOfClassContainingHeritageClause(node);
var baseType = ts.firstOrUndefined(getBaseTypes(classType));
return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
}
@@ -54671,6 +55488,9 @@ var ts;
}
return errorType;
}
+ function getTypeOfClassContainingHeritageClause(node) {
+ return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent));
+ }
// Gets the type of object literal or array literal of destructuring assignment.
// { a } from
// for ( { a } of elems) {
@@ -54732,6 +55552,22 @@ var ts;
? getTypeOfSymbol(classSymbol)
: getDeclaredTypeOfSymbol(classSymbol);
}
+ function getClassElementPropertyKeyType(element) {
+ var name = element.name;
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ return getLiteralType(ts.idText(name));
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ return getLiteralType(name.text);
+ case 147 /* ComputedPropertyName */:
+ var nameType = checkComputedPropertyName(name);
+ return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType;
+ default:
+ ts.Debug.fail("Unsupported property name.");
+ return errorType;
+ }
+ }
// Return the list of properties of the given type, augmented with properties from Function
// if the type has call or construct signatures
function getAugmentedPropertiesOfType(type) {
@@ -54799,13 +55635,13 @@ var ts;
// for export assignments - check if resolved symbol for RHS is itself a value
// otherwise - check if at least one export is value
symbolLinks.exportsSomeValue = hasExportAssignment
- ? !!(moduleSymbol.flags & 67216319 /* Value */)
+ ? !!(moduleSymbol.flags & 67220415 /* Value */)
: ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
}
return symbolLinks.exportsSomeValue;
function isValue(s) {
s = resolveSymbol(s);
- return s && !!(s.flags & 67216319 /* Value */);
+ return s && !!(s.flags & 67220415 /* Value */);
}
}
function isNameOfModuleOrEnumDeclaration(node) {
@@ -54854,7 +55690,7 @@ var ts;
var symbol = getReferencedValueSymbol(node);
// We should only get the declaration of an alias if there isn't a local value
// declaration for the symbol
- if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) {
+ if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) {
return getDeclarationOfAliasSymbol(symbol);
}
}
@@ -54867,7 +55703,7 @@ var ts;
var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
if (ts.isStatementWithLocals(container)) {
var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
- if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
+ if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
// redeclaration - always should be renamed
links.isDeclarationWithCollidingName = true;
}
@@ -54963,7 +55799,7 @@ var ts;
}
// const enums and modules that contain only const enums are not considered values from the emit perspective
// unless 'preserveConstEnums' option is set to true
- return !!(target.flags & 67216319 /* Value */) &&
+ return !!(target.flags & 67220415 /* Value */) &&
(compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
}
function isConstEnumOrConstEnumOnlyModule(s) {
@@ -54976,7 +55812,7 @@ var ts;
return true;
}
var target = getSymbolLinks(symbol).target; // TODO: GH#18217
- if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) {
+ if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) {
// An `export import ... =` of a value symbol is always considered referenced
return true;
}
@@ -55021,6 +55857,25 @@ var ts;
!parameter.initializer &&
ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
}
+ function isJSContainerFunctionDeclaration(node) {
+ var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
+ if (!declaration) {
+ return false;
+ }
+ var symbol = getSymbolOfNode(declaration);
+ if (!symbol || !(symbol.flags & 16 /* Function */)) {
+ return false;
+ }
+ return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return ts.isPropertyAccessExpression(p.valueDeclaration); });
+ }
+ function getPropertiesOfContainerFunction(node) {
+ var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
+ if (!declaration) {
+ return ts.emptyArray;
+ }
+ var symbol = getSymbolOfNode(declaration);
+ return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
+ }
function getNodeCheckFlags(node) {
return getNodeLinks(node).flags || 0;
}
@@ -55065,9 +55920,9 @@ var ts;
return ts.TypeReferenceSerializationKind.Unknown;
}
// Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
- var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
+ var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
// Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
- var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
+ var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
if (valueSymbol && valueSymbol === typeSymbol) {
var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
@@ -55169,7 +56024,7 @@ var ts;
location = getDeclarationContainer(parent);
}
}
- return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
+ return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
}
function getReferencedValueDeclaration(referenceIn) {
if (!ts.isGeneratedIdentifier(referenceIn)) {
@@ -55184,18 +56039,19 @@ var ts;
return undefined;
}
function isLiteralConstDeclaration(node) {
- if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
+ if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
var type = getTypeOfSymbol(getSymbolOfNode(node));
return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */);
}
return false;
}
- function literalTypeToNode(type) {
- return ts.createLiteral(type.value);
+ function literalTypeToNode(type, enclosing) {
+ var enumResult = type.flags & 512 /* EnumLiteral */ && nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing);
+ return enumResult || ts.createLiteral(type.value);
}
function createLiteralConstValue(node) {
var type = getTypeOfSymbol(getSymbolOfNode(node));
- return literalTypeToNode(type);
+ return literalTypeToNode(type, node);
}
function createResolver() {
// this variable and functions that use it are deliberately moved here from the outer scope
@@ -55238,6 +56094,8 @@ var ts;
isImplementationOfOverload: isImplementationOfOverload,
isRequiredInitializedParameter: isRequiredInitializedParameter,
isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
+ isJSContainerFunctionDeclaration: isJSContainerFunctionDeclaration,
+ getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
createTypeOfDeclaration: createTypeOfDeclaration,
createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
createTypeOfExpression: createTypeOfExpression,
@@ -55293,9 +56151,9 @@ var ts;
// property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
// qualified names can only be used as types\namespaces
// identifiers are treated as values only if they appear in type queries
- var meaning = 67901928 /* Type */ | 1920 /* Namespace */;
+ var meaning = 67897832 /* Type */ | 1920 /* Namespace */;
if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
- meaning = 67216319 /* Value */ | 1048576 /* ExportValue */;
+ meaning = 67220415 /* Value */ | 1048576 /* ExportValue */;
}
var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
@@ -55491,7 +56349,7 @@ var ts;
for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) {
if (uncheckedHelpers & helper) {
var name = getHelperName(helper);
- var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */);
+ var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */);
if (!symbol) {
error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name);
}
@@ -55865,11 +56723,32 @@ var ts;
}
}
}
+ function getNonSimpleParameters(parameters) {
+ return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
+ }
+ function checkGrammarForUseStrictSimpleParameterList(node) {
+ if (languageVersion >= 3 /* ES2016 */) {
+ var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
+ if (useStrictDirective_1) {
+ var nonSimpleParameters = getNonSimpleParameters(node.parameters);
+ if (ts.length(nonSimpleParameters)) {
+ ts.forEach(nonSimpleParameters, function (parameter) {
+ addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
+ });
+ var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
+ addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
+ return true;
+ }
+ }
+ }
+ return false;
+ }
function checkGrammarFunctionLikeDeclaration(node) {
// Prevent cascading error by short-circuit
var file = ts.getSourceFileOfNode(node);
return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
- checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file);
+ checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
+ (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
}
function checkGrammarClassLikeDeclaration(node) {
var file = ts.getSourceFileOfNode(node);
@@ -55943,8 +56822,8 @@ var ts;
}
function checkGrammarForOmittedArgument(args) {
if (args) {
- for (var _i = 0, args_5 = args; _i < args_5.length; _i++) {
- var arg = args_5[_i];
+ for (var _i = 0, args_6 = args; _i < args_6.length; _i++) {
+ var arg = args_6[_i];
if (arg.kind === 208 /* OmittedExpression */) {
return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
}
@@ -56047,6 +56926,9 @@ var ts;
function checkGrammarForInvalidQuestionMark(questionToken, message) {
return !!questionToken && grammarErrorOnNode(questionToken, message);
}
+ function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
+ return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
+ }
function checkGrammarObjectLiteralExpression(node, inDestructuring) {
var Flags;
(function (Flags) {
@@ -56090,8 +56972,10 @@ var ts;
// and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
var currentKind = void 0;
switch (prop.kind) {
- case 273 /* PropertyAssignment */:
case 274 /* ShorthandPropertyAssignment */:
+ checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
+ /* tslint:disable:no-switch-case-fall-through */
+ case 273 /* PropertyAssignment */:
// Grammar checking for computedPropertyName and shorthandPropertyAssignment
checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
if (name.kind === 8 /* NumericLiteral */) {
@@ -56308,6 +57192,9 @@ var ts;
else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
return true;
}
+ else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
+ return true;
+ }
else if (node.body === undefined) {
return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
}
@@ -56404,26 +57291,32 @@ var ts;
expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ &&
expr.operand.kind === 8 /* NumericLiteral */;
}
+ function isSimpleLiteralEnumReference(expr) {
+ if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
+ ts.isEntityNameExpression(expr.expression))
+ return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */);
+ }
+ function checkAmbientInitializer(node) {
+ if (node.initializer) {
+ var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer));
+ var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
+ if (isConstOrReadonly && !node.type) {
+ if (isInvalidInitializer) {
+ return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
+ }
+ }
+ else {
+ return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
+ }
+ if (!isConstOrReadonly || isInvalidInitializer) {
+ return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
+ }
+ }
+ }
function checkGrammarVariableDeclaration(node) {
if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) {
if (node.flags & 4194304 /* Ambient */) {
- if (node.initializer) {
- if (ts.isVarConst(node) && !node.type) {
- if (!isStringOrNumberLiteralExpression(node.initializer)) {
- return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal);
- }
- }
- else {
- // Error on equals token which immediate precedes the initializer
- var equalsTokenLength = "=".length;
- return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
- }
- }
- if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) {
- // Error on equals token which immediate precedes the initializer
- var equalsTokenLength = "=".length;
- return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
- }
+ checkAmbientInitializer(node);
}
else if (!node.initializer) {
if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
@@ -56597,8 +57490,8 @@ var ts;
return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
}
}
- if (node.flags & 4194304 /* Ambient */ && node.initializer) {
- return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
+ if (node.flags & 4194304 /* Ambient */) {
+ checkAmbientInitializer(node);
}
if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
@@ -60174,6 +61067,21 @@ var ts;
return statementOffset;
}
ts.addCustomPrologue = addCustomPrologue;
+ function findUseStrictPrologue(statements) {
+ for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
+ var statement = statements_3[_i];
+ if (ts.isPrologueDirective(statement)) {
+ if (isUseStrictPrologue(statement)) {
+ return statement;
+ }
+ }
+ else {
+ break;
+ }
+ }
+ return undefined;
+ }
+ ts.findUseStrictPrologue = findUseStrictPrologue;
function startsWithUseStrict(statements) {
var firstStatement = ts.firstOrUndefined(statements);
return firstStatement !== undefined
@@ -60187,19 +61095,7 @@ var ts;
* @param statements An array of statements
*/
function ensureUseStrict(statements) {
- var foundUseStrict = false;
- for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
- var statement = statements_3[_i];
- if (ts.isPrologueDirective(statement)) {
- if (isUseStrictPrologue(statement)) {
- foundUseStrict = true;
- break;
- }
- }
- else {
- break;
- }
- }
+ var foundUseStrict = findUseStrictPrologue(statements);
if (!foundUseStrict) {
return ts.setTextRange(ts.createNodeArray([
startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
@@ -69210,19 +70106,27 @@ var ts;
ts.setOriginalNode(declarationList, node);
ts.setTextRange(declarationList, node);
ts.setCommentRange(declarationList, node);
+ // If the first or last declaration is a binding pattern, we need to modify
+ // the source map range for the declaration list.
if (node.transformFlags & 8388608 /* ContainsBindingPattern */
&& (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
- // If the first or last declaration is a binding pattern, we need to modify
- // the source map range for the declaration list.
- var firstDeclaration = ts.firstOrUndefined(declarations);
- if (firstDeclaration) {
- ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end));
- }
+ ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
}
return declarationList;
}
return ts.visitEachChild(node, visitor, context);
}
+ function getRangeUnion(declarations) {
+ // declarations may not be sorted by position.
+ // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
+ var pos = -1, end = -1;
+ for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
+ var node = declarations_10[_i];
+ pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
+ end = Math.max(end, node.end);
+ }
+ return ts.createRange(pos, end);
+ }
/**
* Gets a value indicating whether we should emit an explicit initializer for a variable
* declaration in a `let` declaration list.
@@ -73529,7 +74433,10 @@ var ts;
* @param node The SourceFile node.
*/
function transformSourceFile(node) {
- if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) {
+ if (node.isDeclarationFile ||
+ !(ts.isEffectiveExternalModule(node, compilerOptions) ||
+ node.transformFlags & 67108864 /* ContainsDynamicImport */ ||
+ (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
return node;
}
currentSourceFile = node;
@@ -73583,6 +74490,7 @@ var ts;
function transformAMDModule(node) {
var define = ts.createIdentifier("define");
var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
+ var jsonSourceFile = ts.isJsonSourceFile(node) && node;
// An AMD define function has the following shape:
//
// define(id?, dependencies?, factory);
@@ -73613,22 +74521,24 @@ var ts;
// Add the dependency array argument:
//
// ["require", "exports", module1", "module2", ...]
- ts.createArrayLiteral([
+ ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [
ts.createLiteral("require"),
ts.createLiteral("exports")
].concat(aliasedModuleNames, unaliasedModuleNames)),
// Add the module body function argument:
//
// function (require, exports, module1, module2) ...
- ts.createFunctionExpression(
- /*modifiers*/ undefined,
- /*asteriskToken*/ undefined,
- /*name*/ undefined,
- /*typeParameters*/ undefined, [
- ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
- ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
- ].concat(importAliasNames),
- /*type*/ undefined, transformAsynchronousModuleBody(node))
+ jsonSourceFile ?
+ jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
+ ts.createFunctionExpression(
+ /*modifiers*/ undefined,
+ /*asteriskToken*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, [
+ ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
+ ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
+ ].concat(importAliasNames),
+ /*type*/ undefined, transformAsynchronousModuleBody(node))
])))
]),
/*location*/ node.statements));
@@ -76851,7 +77761,7 @@ var ts;
var needsScopeFixMarker = false;
var resultHasScopeMarker = false;
var enclosingDeclaration;
- var necessaryTypeRefernces;
+ var necessaryTypeReferences;
var lateMarkedStatements;
var lateStatementReplacementMap;
var suppressNewDiagnosticContexts;
@@ -76869,6 +77779,7 @@ var ts;
var errorNameNode;
var currentSourceFile;
var refs;
+ var libs;
var resolver = context.getEmitResolver();
var options = context.getCompilerOptions();
var newLine = ts.getNewLineCharacter(options);
@@ -76878,10 +77789,10 @@ var ts;
if (!typeReferenceDirectives) {
return;
}
- necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap();
+ necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
var ref = typeReferenceDirectives_2[_i];
- necessaryTypeRefernces.set(ref, true);
+ necessaryTypeReferences.set(ref, true);
}
}
function trackReferencedAmbientModule(node, symbol) {
@@ -76956,6 +77867,7 @@ var ts;
if (node.kind === 278 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
+ libs = ts.createMap();
var hasNoDefaultLib_1 = false;
var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile))
@@ -76970,6 +77882,7 @@ var ts;
needsScopeFixMarker = false;
resultHasScopeMarker = false;
collectReferences(sourceFile, refs);
+ collectLibs(sourceFile, libs);
if (ts.isExternalModule(sourceFile)) {
resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
needsDeclare = false;
@@ -76987,6 +77900,7 @@ var ts;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
+ bundle.syntheticLibReferences = getLibReferences();
bundle.hasNoDefaultLib = hasNoDefaultLib_1;
var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
@@ -77005,8 +77919,9 @@ var ts;
suppressNewDiagnosticContexts = false;
lateMarkedStatements = undefined;
lateStatementReplacementMap = ts.createMap();
- necessaryTypeRefernces = undefined;
+ necessaryTypeReferences = undefined;
refs = collectReferences(currentSourceFile, ts.createMap());
+ libs = collectLibs(currentSourceFile, ts.createMap());
var references = [];
var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
@@ -77017,11 +77932,14 @@ var ts;
if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements);
}
- var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib);
+ var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
return updated;
+ function getLibReferences() {
+ return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
+ }
function getFileReferencesForUsedTypeReferences() {
- return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : [];
+ return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
}
function getFileReferenceForTypeName(typeName) {
// Elide type references for which we have imports
@@ -77059,6 +77977,11 @@ var ts;
if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
fileName = fileName.substring(2);
}
+ // omit references to files from node_modules (npm may disambiguate module
+ // references when installing this package, making the path is unreliable).
+ if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) {
+ return;
+ }
references.push({ pos: -1, end: -1, fileName: fileName });
}
};
@@ -77075,6 +77998,15 @@ var ts;
});
return ret;
}
+ function collectLibs(sourceFile, ret) {
+ ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
+ var lib = host.getLibFileFromReference(ref);
+ if (lib) {
+ ret.set(ref.fileName.toLocaleLowerCase(), true);
+ }
+ });
+ return ret;
+ }
function filterBindingPatternInitializers(name) {
if (name.kind === 71 /* Identifier */) {
return name;
@@ -77591,10 +78523,25 @@ var ts;
}
case 237 /* FunctionDeclaration */: {
// Generators lose their generator-ness, excepting their return type
- return cleanup(ts.updateFunctionDeclaration(input,
+ var clean = cleanup(ts.updateFunctionDeclaration(input,
/*decorators*/ undefined, ensureModifiers(input, isPrivate),
/*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type),
/*body*/ undefined));
+ if (clean && resolver.isJSContainerFunctionDeclaration(input)) {
+ var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) {
+ if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
+ return undefined;
+ }
+ var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
+ var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
+ });
+ var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
+ return [clean, namespaceDecl];
+ }
+ else {
+ return clean;
+ }
}
case 242 /* ModuleDeclaration */: {
needsDeclare = false;
@@ -77878,10 +78825,11 @@ var ts;
}
function canHaveLiteralInitializer(node) {
switch (node.kind) {
- case 235 /* VariableDeclaration */:
case 152 /* PropertyDeclaration */:
case 151 /* PropertySignature */:
+ return !ts.hasModifier(node, 8 /* Private */);
case 149 /* Parameter */:
+ case 235 /* VariableDeclaration */:
return true;
}
return false;
@@ -80634,7 +81582,9 @@ var ts;
}
function emitExpressionStatement(node) {
emitExpression(node.expression);
- if (!ts.isJsonSourceFile(currentSourceFile)) {
+ // Emit semicolon in non json files
+ // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
+ if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
writeSemicolon();
}
}
@@ -81337,13 +82287,13 @@ var ts;
emitSourceFileWorker(node);
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
- emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []);
+ emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
- emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives);
+ emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
}
- function emitTripleSlashDirectives(hasNoDefaultLib, files, types) {
+ function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
write("/// ");
writeLine();
@@ -81369,11 +82319,16 @@ var ts;
write("/// ");
writeLine();
}
- for (var _d = 0, types_17 = types; _d < types_17.length; _d++) {
- var directive = types_17[_d];
+ for (var _d = 0, types_16 = types; _d < types_16.length; _d++) {
+ var directive = types_16[_d];
write("/// ");
writeLine();
}
+ for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
+ var directive = libs_1[_e];
+ write("/// ");
+ writeLine();
+ }
}
function emitSourceFileWorker(node) {
var statements = node.statements;
@@ -81538,7 +82493,8 @@ var ts;
var parameter = ts.singleOrUndefined(parameters);
return parameter
&& parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
- && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation
+ && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
+ && !parentNode.type // arrow function may not have return type annotation
&& !ts.some(parentNode.decorators) // parent may not have decorators
&& !ts.some(parentNode.modifiers) // parent may not have modifiers
&& !ts.some(parentNode.typeParameters) // parent may not have type parameters
@@ -82150,7 +83106,7 @@ var ts;
if (node.locals) {
var local = node.locals.get(ts.escapeLeadingUnderscores(name));
// We conservatively include alias symbols to cover cases where they're emitted as locals
- if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
+ if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
return false;
}
}
@@ -82743,17 +83699,24 @@ var ts;
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
function createCompilerHost(options, setParentNodes) {
+ return createCompilerHostWorker(options, setParentNodes);
+ }
+ ts.createCompilerHost = createCompilerHost;
+ /*@internal*/
+ // TODO(shkamat): update this after reworking ts build API
+ function createCompilerHostWorker(options, setParentNodes, system) {
+ if (system === void 0) { system = ts.sys; }
var existingDirectories = ts.createMap();
function getCanonicalFileName(fileName) {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
// otherwise use toLowerCase as a canonical form.
- return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
+ return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
ts.performance.mark("beforeIORead");
- text = ts.sys.readFile(fileName, options.charset);
+ text = system.readFile(fileName, options.charset);
ts.performance.mark("afterIORead");
ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
@@ -82769,7 +83732,7 @@ var ts;
if (existingDirectories.has(directoryPath)) {
return true;
}
- if (ts.sys.directoryExists(directoryPath)) {
+ if (system.directoryExists(directoryPath)) {
existingDirectories.set(directoryPath, true);
return true;
}
@@ -82779,7 +83742,7 @@ var ts;
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
- ts.sys.createDirectory(directoryPath);
+ system.createDirectory(directoryPath);
}
}
var outputFingerprints;
@@ -82787,8 +83750,8 @@ var ts;
if (!outputFingerprints) {
outputFingerprints = ts.createMap();
}
- var hash = ts.sys.createHash(data); // TODO: GH#18217
- var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217
+ var hash = system.createHash(data); // TODO: GH#18217
+ var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217
if (mtimeBefore) {
var fingerprint = outputFingerprints.get(fileName);
// If output has not been changed, and the file has no external modification
@@ -82799,8 +83762,8 @@ var ts;
return;
}
}
- ts.sys.writeFile(fileName, data, writeByteOrderMark);
- var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217
+ system.writeFile(fileName, data, writeByteOrderMark);
+ var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217
outputFingerprints.set(fileName, {
hash: hash,
byteOrderMark: writeByteOrderMark,
@@ -82811,11 +83774,11 @@ var ts;
try {
ts.performance.mark("beforeIOWrite");
ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName)));
- if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) {
+ if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) {
writeFileIfUpdated(fileName, data, writeByteOrderMark);
}
else {
- ts.sys.writeFile(fileName, data, writeByteOrderMark);
+ system.writeFile(fileName, data, writeByteOrderMark);
}
ts.performance.mark("afterIOWrite");
ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
@@ -82827,33 +83790,30 @@ var ts;
}
}
function getDefaultLibLocation() {
- return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath()));
+ return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
}
- var newLine = ts.getNewLineCharacter(options);
- var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); });
+ var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
+ var realpath = system.realpath && (function (path) { return system.realpath(path); });
return {
getSourceFile: getSourceFile,
getDefaultLibLocation: getDefaultLibLocation,
getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
writeFile: writeFile,
- getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }),
- useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; },
+ getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
+ useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
getCanonicalFileName: getCanonicalFileName,
getNewLine: function () { return newLine; },
- fileExists: function (fileName) { return ts.sys.fileExists(fileName); },
- readFile: function (fileName) { return ts.sys.readFile(fileName); },
- trace: function (s) { return ts.sys.write(s + newLine); },
- directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); },
- getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; },
- getDirectories: function (path) { return ts.sys.getDirectories(path); },
+ fileExists: function (fileName) { return system.fileExists(fileName); },
+ readFile: function (fileName) { return system.readFile(fileName); },
+ trace: function (s) { return system.write(s + newLine); },
+ directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
+ getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
+ getDirectories: function (path) { return system.getDirectories(path); },
realpath: realpath,
- readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); },
- getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }),
- setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }),
- deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); })
+ readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }
};
}
- ts.createCompilerHost = createCompilerHost;
+ ts.createCompilerHostWorker = createCompilerHostWorker;
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (program.getCompilerOptions().declaration) {
@@ -82864,8 +83824,8 @@ var ts;
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
- for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
- var diagnostic = diagnostics_1[_i];
+ for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
+ var diagnostic = diagnostics_2[_i];
output += formatDiagnostic(diagnostic, host);
}
return output;
@@ -82979,8 +83939,8 @@ var ts;
ts.formatLocation = formatLocation;
function formatDiagnosticsWithColorAndContext(diagnostics, host) {
var output = "";
- for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
- var diagnostic = diagnostics_2[_i];
+ for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
+ var diagnostic = diagnostics_3[_i];
if (diagnostic.file) {
var file = diagnostic.file, start = diagnostic.start;
output += formatLocation(file, start, host); // TODO: GH#18217
@@ -82995,11 +83955,11 @@ var ts;
if (diagnostic.relatedInformation) {
output += host.getNewLine();
for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
- var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText;
+ var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText;
if (file) {
output += host.getNewLine();
output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
- output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
+ output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
}
output += host.getNewLine();
output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
@@ -83391,13 +84351,13 @@ var ts;
// which per above occurred during the current program creation.
// Since we assume the filesystem does not change during program creation,
// it is safe to reuse resolutions from the earlier call.
- var result_4 = [];
+ var result_5 = [];
for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
var moduleName = moduleNames_1[_i];
var resolvedModule = file.resolvedModules.get(moduleName);
- result_4.push(resolvedModule);
+ result_5.push(resolvedModule);
}
- return result_4;
+ return result_5;
}
// At this point, we know at least one of the following hold:
// - file has local declarations for ambient modules
@@ -83482,8 +84442,11 @@ var ts;
// If we change our policy of rechecking failed lookups on each program create,
// we should adjust the value returned here.
function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) {
+ if (!oldProgramState.program) {
+ return false;
+ }
var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217
- var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName);
+ var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName);
if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) {
// In the old program, we resolved to an ambient module that was in the same
// place as we expected to find an actual module file.
@@ -83491,15 +84454,8 @@ var ts;
// because the normal module resolution algorithm will find this anyway.
return false;
}
- var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName);
- if (!(ambientModule && ambientModule.declarations)) {
- return false;
- }
// at least one of declarations should come from non-modified source file
- var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) {
- var f = ts.getSourceFileOfNode(d);
- return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f;
- });
+ var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); });
if (!firstUnmodifiedFile) {
return false;
}
@@ -83686,7 +84642,8 @@ var ts;
}
}
if (resolveTypeReferenceDirectiveNamesWorker) {
- var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; });
+ // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
+ var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); });
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath);
// ensure that types resolutions are still correct
var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
@@ -83728,7 +84685,7 @@ var ts;
}
function getEmitHost(writeFileCallback) {
return __assign({ getPrependNodes: getPrependNodes,
- getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) {
+ getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) {
// Use local caches
var path = toPath(f);
if (getSourceFileByPath(path))
@@ -83740,8 +84697,6 @@ var ts;
} }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
}
function getProjectReferences() {
- if (!resolvedProjectReferences)
- return;
return resolvedProjectReferences;
}
function getPrependNodes() {
@@ -84662,27 +85617,19 @@ var ts;
}
}
function computeCommonSourceDirectory(sourceFiles) {
- var fileNames = [];
- for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
- var file = sourceFiles_2[_i];
- if (!file.isDeclarationFile) {
- fileNames.push(file.fileName);
- }
- }
+ var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
}
function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
var allFilesBelongToPath = true;
- if (sourceFiles) {
- var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
- for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
- var sourceFile = sourceFiles_3[_i];
- if (!sourceFile.isDeclarationFile) {
- var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
- if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
- programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory));
- allFilesBelongToPath = false;
- }
+ var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
+ for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
+ var sourceFile = sourceFiles_2[_i];
+ if (!sourceFile.isDeclarationFile) {
+ var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
+ if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory));
+ allFilesBelongToPath = false;
}
}
}
@@ -84768,17 +85715,16 @@ var ts;
}
}
// List of collected files is complete; validate exhautiveness if this is a project with a file list
- if (options.composite && rootNames.length < files.length) {
- var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
- var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); });
- var _loop_9 = function (file) {
- if (normalizedRootNames.every(function (r) { return r !== file; })) {
- programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file));
+ if (options.composite) {
+ var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; });
+ if (rootNames.length < sourceFiles.length) {
+ var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
+ for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) {
+ var file = _a[_i];
+ if (normalizedRootNames.indexOf(file) === -1) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file));
+ }
}
- };
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var file = sourceFiles_4[_i];
- _loop_9(file);
}
}
if (options.paths) {
@@ -84876,9 +85822,9 @@ var ts;
if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
}
- // Any emit other than common js is error
- else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) {
- createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module");
+ // Any emit other than common js, amd, es2015 or esnext is error
+ else if (!ts.hasJsonModuleEmitEnabled(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
}
}
// there has to be common source directory if user specified --outdir || --sourceRoot
@@ -86588,121 +87534,117 @@ var ts;
(function (ts) {
var moduleSpecifiers;
(function (moduleSpecifiers) {
+ var RelativePreference;
+ (function (RelativePreference) {
+ RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
+ RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
+ RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
+ })(RelativePreference || (RelativePreference = {}));
+ // See UserPreferences#importPathEnding
+ var Ending;
+ (function (Ending) {
+ Ending[Ending["Minimal"] = 0] = "Minimal";
+ Ending[Ending["Index"] = 1] = "Index";
+ Ending[Ending["JsExtension"] = 2] = "JsExtension";
+ })(Ending || (Ending = {}));
+ function getPreferences(_a, compilerOptions, importingSourceFile) {
+ var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
+ return {
+ relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
+ ending: getEnding(),
+ };
+ function getEnding() {
+ switch (importModuleSpecifierEnding) {
+ case "minimal": return 0 /* Minimal */;
+ case "index": return 1 /* Index */;
+ case "js": return 2 /* JsExtension */;
+ default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
+ : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
+ }
+ }
+ }
+ function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
+ return {
+ relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
+ ending: ts.hasJavaScriptOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */
+ : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
+ };
+ }
+ function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) {
+ var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
+ if (res === oldImportSpecifier)
+ return undefined;
+ return res;
+ }
+ moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
// Note: importingSourceFile is just for usesJsExtensionOnImports
function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) {
if (preferences === void 0) { preferences = {}; }
- var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host);
- var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap);
- return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) ||
- ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences));
+ return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile));
}
moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
- function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) {
- var isBundle = (compilerOptions.out || compilerOptions.outFile);
- if (isBundle && host.getCommonSourceDirectory) {
- // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
- // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
- // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
- // specifier preference
- compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() });
- }
- var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" };
- return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap)));
+ function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) {
+ var info = getInfo(importingSourceFileName, host);
+ var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap);
+ return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
+ getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
}
- moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile;
- // For each symlink/original for a module, returns a list of ways to import that file.
- function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) {
+ // Returns an import for each symlink and for the realpath.
+ function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) {
var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
if (ambient)
- return [[ambient]];
- var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host);
- if (!files) {
- return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution");
- }
+ return [ambient];
+ var info = getInfo(importingSourceFile.path, host);
var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap);
- var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); });
- return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) {
- return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences);
- });
+ var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
+ var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
+ return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
}
moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
// importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
- function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) {
- var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions);
- var addJsExtension = usesJsExtensionOnImports(importingSourceFile);
+ function getInfo(importingSourceFileName, host) {
var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
- return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
+ return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
}
- function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) {
- var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
- return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension)
- || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory);
- }
- function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) {
- var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
+ function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
+ var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
+ var ending = _b.ending, relativePreference = _b.relativePreference;
var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) ||
- removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension);
- if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
- return [relativePath];
+ removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
+ if (!baseUrl || relativePreference === 0 /* Relative */) {
+ return relativePath;
}
var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
if (!relativeToBaseUrl) {
- return [relativePath];
+ return relativePath;
}
- var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension);
- if (paths) {
- var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
- if (fromPaths) {
- return [fromPaths];
- }
+ var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
+ var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
+ var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
+ if (relativePreference === 1 /* NonRelative */) {
+ return nonRelative;
}
- if (preferences.importModuleSpecifierPreference === "non-relative") {
- return [importRelativeToBaseUrl];
+ if (relativePreference !== 2 /* Auto */)
+ ts.Debug.assertNever(relativePreference);
+ // Prefer a relative import over a baseUrl import if it has fewer components.
+ return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
+ }
+ function countPathComponents(path) {
+ var count = 0;
+ for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
+ if (path.charCodeAt(i) === 47 /* slash */)
+ count++;
}
- if (preferences.importModuleSpecifierPreference !== undefined)
- ts.Debug.assertNever(preferences.importModuleSpecifierPreference);
- if (isPathRelativeToParent(relativeToBaseUrl)) {
- return [relativePath];
- }
- /*
- Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl.
-
- Suppose we have:
- baseUrl = /base
- sourceDirectory = /base/a/b
- moduleFileName = /base/foo/bar
- Then:
- relativePath = ../../foo/bar
- getRelativePathNParents(relativePath) = 2
- pathFromSourceToBaseUrl = ../../
- getRelativePathNParents(pathFromSourceToBaseUrl) = 2
- 2 < 2 = false
- In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar".
-
- Suppose we have:
- baseUrl = /base
- sourceDirectory = /base/foo/a
- moduleFileName = /base/foo/bar
- Then:
- relativePath = ../a
- getRelativePathNParents(relativePath) = 1
- pathFromSourceToBaseUrl = ../../
- getRelativePathNParents(pathFromSourceToBaseUrl) = 2
- 1 < 2 = true
- In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
- */
- var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName));
- var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
- return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
+ return count;
}
function usesJsExtensionOnImports(_a) {
var imports = _a.imports;
return ts.firstDefined(imports, function (_a) {
var text = _a.text;
- return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined;
+ return ts.pathIsRelative(text) ? ts.hasJavaScriptOrJsonFileExtension(text) : undefined;
}) || false;
}
function stringsEqual(a, b, getCanonicalFileName) {
@@ -86766,16 +87708,6 @@ var ts;
result.push.apply(result, targets);
return result;
}
- function getRelativePathNParents(relativePath) {
- var components = ts.getPathComponents(relativePath);
- if (components[0] || components.length === 1)
- return 0;
- for (var i = 1; i < components.length; i++) {
- if (components[i] !== "..")
- return i - 1;
- }
- return components.length - 1;
- }
function tryGetModuleNameFromAmbientModule(moduleSymbol) {
var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
if (decl) {
@@ -86793,7 +87725,8 @@ var ts;
var suffix = pattern.substr(indexOfStar + 1);
if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
ts.startsWith(relativeToBaseUrl, prefix) &&
- ts.endsWith(relativeToBaseUrl, suffix)) {
+ ts.endsWith(relativeToBaseUrl, suffix) ||
+ !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
return key.replace("*", matchedStar);
}
@@ -86813,25 +87746,27 @@ var ts;
var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
return ts.removeFileExtension(relativePath);
}
- function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
- var roots = ts.getEffectiveTypeRoots(options, host);
- return ts.firstDefined(roots, function (unNormalizedTypeRoot) {
- var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName);
- if (ts.startsWith(moduleFileName, typeRoot)) {
- // For a type definition, we can strip `/index` even with classic resolution.
- return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension);
- }
- });
- }
- function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) {
- if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
- // nothing to do here
- return undefined;
- }
+ function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) {
+ var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
var parts = getNodeModulePathParts(moduleFileName);
if (!parts) {
return undefined;
}
+ var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex);
+ var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
+ var packageJsonContent = host.fileExists(packageJsonPath)
+ ? JSON.parse(host.readFile(packageJsonPath))
+ : undefined;
+ var versionPaths = packageJsonContent && packageJsonContent.typesVersions
+ ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
+ : undefined;
+ if (versionPaths) {
+ var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1);
+ var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
+ if (fromPaths !== undefined) {
+ moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths);
+ }
+ }
// Simplify the full file path to something that can be resolved by Node.
// If the module could be imported by a directory name, use that directory's name
var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
@@ -86840,20 +87775,18 @@ var ts;
if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex))))
return undefined;
// If the module was found in @types, get the actual Node package name
- return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1));
+ var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
+ var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
+ // For classic resolution, only allow importing from node_modules/@types, not other node_modules
+ return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
function getDirectoryOrExtensionlessFileName(path) {
// If the file is the main module, it can be imported by the package name
- var packageRootPath = path.substring(0, parts.packageRootIndex);
- var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
- if (host.fileExists(packageJsonPath)) { // TODO: GH#18217
- var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
- if (packageJsonContent) {
- var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
- if (mainFileRelative) {
- var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
- if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) {
- return packageRootPath;
- }
+ if (packageJsonContent) {
+ var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
+ if (mainFileRelative) {
+ var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
+ if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) {
+ return packageRootPath;
}
}
}
@@ -86936,13 +87869,36 @@ var ts;
return isPathRelativeToParent(relativePath) ? undefined : relativePath;
});
}
- function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) {
+ function removeExtensionAndIndexPostFix(fileName, ending, options) {
+ if (ts.fileExtensionIs(fileName, ".json" /* Json */))
+ return fileName;
var noExtension = ts.removeFileExtension(fileName);
- return addJsExtension
- ? noExtension + ".js"
- : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs
- ? ts.removeSuffix(noExtension, "/index")
- : noExtension;
+ switch (ending) {
+ case 0 /* Minimal */:
+ return ts.removeSuffix(noExtension, "/index");
+ case 1 /* Index */:
+ return noExtension;
+ case 2 /* JsExtension */:
+ return noExtension + getJavaScriptExtensionForFile(fileName, options);
+ default:
+ return ts.Debug.assertNever(ending);
+ }
+ }
+ function getJavaScriptExtensionForFile(fileName, options) {
+ var ext = ts.extensionFromPath(fileName);
+ switch (ext) {
+ case ".ts" /* Ts */:
+ case ".d.ts" /* Dts */:
+ return ".js" /* Js */;
+ case ".tsx" /* Tsx */:
+ return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
+ case ".js" /* Js */:
+ case ".jsx" /* Jsx */:
+ case ".json" /* Json */:
+ return ext;
+ default:
+ return ts.Debug.assertNever(ext);
+ }
}
function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
@@ -86981,11 +87937,6 @@ var ts;
};
}
ts.createDiagnosticReporter = createDiagnosticReporter;
- /** @internal */
- ts.nonClearingMessageCodes = [
- ts.Diagnostics.Found_1_error_Watching_for_file_changes.code,
- ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code
- ];
/**
* @returns Whether the screen was cleared.
*/
@@ -86994,7 +87945,7 @@ var ts;
!options.preserveWatchOutput &&
!options.extendedDiagnostics &&
!options.diagnostics &&
- !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) {
+ ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
system.clearScreen();
return true;
}
@@ -87094,6 +88045,25 @@ var ts;
}
ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
var noopFileWatcher = { close: ts.noop };
+ function createWatchHost(system, reportWatchStatus) {
+ if (system === void 0) { system = ts.sys; }
+ var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
+ return {
+ onWatchStatusChange: onWatchStatusChange,
+ watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; },
+ watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; },
+ setTimeout: system.setTimeout ? (function (callback, ms) {
+ var args = [];
+ for (var _i = 2; _i < arguments.length; _i++) {
+ args[_i - 2] = arguments[_i];
+ }
+ var _a;
+ return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args));
+ }) : ts.noop,
+ clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop
+ };
+ }
+ ts.createWatchHost = createWatchHost;
/**
* Creates the watch compiler host that can be extended with config file or root file names and options host
*/
@@ -87106,7 +88076,7 @@ var ts;
host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!)
var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; };
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
+ var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout;
return {
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
getNewLine: function () { return system.newLine; },
@@ -87120,17 +88090,10 @@ var ts;
readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
realpath: system.realpath && (function (path) { return system.realpath(path); }),
getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }),
- watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; },
- watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; },
- setTimeout: system.setTimeout ? (function (callback, ms) {
- var args = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- args[_i - 2] = arguments[_i];
- }
- var _a;
- return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args));
- }) : ts.noop,
- clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop,
+ watchFile: watchFile,
+ watchDirectory: watchDirectory,
+ setTimeout: setTimeout,
+ clearTimeout: clearTimeout,
trace: function (s) { return system.write(s); },
onWatchStatusChange: onWatchStatusChange,
createDirectory: function (path) { return system.createDirectory(path); },
@@ -87650,6 +88613,8 @@ var ts;
}
ts.createWatchProgram = createWatchProgram;
})(ts || (ts = {}));
+// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch
+/*@internal*/
var ts;
(function (ts) {
var minimumDate = new Date(-8640000000000000);
@@ -87704,7 +88669,8 @@ var ts;
getValueOrUndefined: getValueOrUndefined,
removeKey: removeKey,
getKeys: getKeys,
- hasKey: hasKey
+ hasKey: hasKey,
+ getSize: getSize
};
function getKeys() {
return Object.keys(lookup);
@@ -87731,6 +88697,9 @@ var ts;
var f = ts.normalizePath(fileName);
return lookup.get(f);
}
+ function getSize() {
+ return lookup.size;
+ }
}
function createDependencyMapper() {
var childToParents = createFileMap();
@@ -87787,7 +88756,11 @@ var ts;
return ts.emptyArray;
}
var outputs = [];
- outputs.push(getOutputJavaScriptFileName(inputFileName, configFile));
+ var js = getOutputJavaScriptFileName(inputFileName, configFile);
+ outputs.push(js);
+ if (configFile.options.sourceMap) {
+ outputs.push(js + ".map");
+ }
if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) {
var dts = getOutputDeclarationFileName(inputFileName, configFile);
outputs.push(dts);
@@ -87803,6 +88776,9 @@ var ts;
}
var outputs = [];
outputs.push(project.options.outFile);
+ if (project.options.sourceMap) {
+ outputs.push(project.options.outFile + ".map");
+ }
if (ts.getEmitDeclarations(project.options)) {
var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */);
outputs.push(dts);
@@ -87843,152 +88819,110 @@ var ts;
return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
}
function createBuildContext(options) {
- var invalidatedProjects = createFileMap();
- var queuedProjects = createFileMap();
+ var invalidatedProjectQueue = [];
+ var nextIndex = 0;
+ var projectPendingBuild = createFileMap();
var missingRoots = ts.createMap();
+ var diagnostics = options.watch ? createFileMap() : undefined;
return {
options: options,
projectStatus: createFileMap(),
+ diagnostics: diagnostics,
unchangedOutputs: createFileMap(),
- invalidatedProjects: invalidatedProjects,
- missingRoots: missingRoots,
- queuedProjects: queuedProjects
+ invalidateProject: invalidateProject,
+ getNextInvalidatedProject: getNextInvalidatedProject,
+ hasPendingInvalidatedProjects: hasPendingInvalidatedProjects,
+ missingRoots: missingRoots
};
+ function invalidateProject(proj, dependencyGraph) {
+ if (!projectPendingBuild.hasKey(proj)) {
+ addProjToQueue(proj);
+ if (dependencyGraph) {
+ queueBuildForDownstreamReferences(proj, dependencyGraph);
+ }
+ }
+ }
+ function addProjToQueue(proj) {
+ ts.Debug.assert(!projectPendingBuild.hasKey(proj));
+ projectPendingBuild.setValue(proj, true);
+ invalidatedProjectQueue.push(proj);
+ }
+ function getNextInvalidatedProject() {
+ if (nextIndex < invalidatedProjectQueue.length) {
+ var proj = invalidatedProjectQueue[nextIndex];
+ nextIndex++;
+ projectPendingBuild.removeKey(proj);
+ if (!projectPendingBuild.getSize()) {
+ invalidatedProjectQueue.length = 0;
+ nextIndex = 0;
+ }
+ return proj;
+ }
+ }
+ function hasPendingInvalidatedProjects() {
+ return !!projectPendingBuild.getSize();
+ }
+ // Mark all downstream projects of this one needing to be built "later"
+ function queueBuildForDownstreamReferences(root, dependencyGraph) {
+ var deps = dependencyGraph.dependencyMap.getReferencesTo(root);
+ for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) {
+ var ref = deps_1[_i];
+ // Can skip circular references
+ if (!projectPendingBuild.hasKey(ref)) {
+ addProjToQueue(ref);
+ queueBuildForDownstreamReferences(ref, dependencyGraph);
+ }
+ }
+ }
}
ts.createBuildContext = createBuildContext;
- var buildOpts = [
- {
- name: "verbose",
- shortName: "v",
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Enable_verbose_logging,
- type: "boolean"
- },
- {
- name: "dry",
- shortName: "d",
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
- type: "boolean"
- },
- {
- name: "force",
- shortName: "f",
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
- type: "boolean"
- },
- {
- name: "clean",
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
- type: "boolean"
- },
- {
- name: "watch",
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Watch_input_files,
- type: "boolean"
- }
- ];
- function performBuild(args, compilerHost, buildHost, system) {
- var verbose = false;
- var dry = false;
- var force = false;
- var clean = false;
- var watch = false;
- var projects = [];
- for (var _i = 0, args_6 = args; _i < args_6.length; _i++) {
- var arg = args_6[_i];
- switch (arg.toLowerCase()) {
- case "-v":
- case "--verbose":
- verbose = true;
- continue;
- case "-d":
- case "--dry":
- dry = true;
- continue;
- case "-f":
- case "--force":
- force = true;
- continue;
- case "--clean":
- clean = true;
- continue;
- case "--watch":
- case "-w":
- watch = true;
- continue;
- case "--?":
- case "-?":
- case "--help":
- ts.printHelp(buildOpts, "--build ");
- return ts.ExitStatus.Success;
- }
- // Not a flag, parse as filename
- addProject(arg);
- }
- // Nonsensical combinations
- if (clean && force) {
- buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force");
- return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
- }
- if (clean && verbose) {
- buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose");
- return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
- }
- if (clean && watch) {
- buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch");
- return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
- }
- if (watch && dry) {
- buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry");
- return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
- }
- if (projects.length === 0) {
- // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
- addProject(".");
- }
- var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system);
- if (clean) {
- return builder.cleanAllProjects();
- }
- if (watch) {
- builder.buildAllProjects();
- builder.startWatching();
- return undefined;
- }
- return builder.buildAllProjects();
- function addProject(projectSpecification) {
- var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification);
- var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName });
- if (!compilerHost.fileExists(refPath)) {
- return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName);
- }
- projects.push(refPath);
- }
+ /**
+ * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
+ */
+ function createBuilderStatusReporter(system, pretty) {
+ return function (diagnostic) {
+ var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - ";
+ output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
+ system.write(output);
+ };
}
- ts.performBuild = performBuild;
+ ts.createBuilderStatusReporter = createBuilderStatusReporter;
+ function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) {
+ if (system === void 0) { system = ts.sys; }
+ var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system);
+ host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; };
+ host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
+ host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
+ host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
+ host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
+ return host;
+ }
+ ts.createSolutionBuilderHost = createSolutionBuilderHost;
+ function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
+ if (system === void 0) { system = ts.sys; }
+ var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus);
+ var watchHost = ts.createWatchHost(system, reportWatchStatus);
+ host.onWatchStatusChange = watchHost.onWatchStatusChange;
+ host.watchFile = watchHost.watchFile;
+ host.watchDirectory = watchHost.watchDirectory;
+ host.setTimeout = watchHost.setTimeout;
+ host.clearTimeout = watchHost.clearTimeout;
+ return host;
+ }
+ ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
/**
* A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but
* can dynamically add/remove other projects based on changes on the rootNames' references
+ * TODO: use SolutionBuilderWithWatchHost => watchedSolution
+ * use SolutionBuilderHost => Solution
*/
- function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) {
- if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) {
- throw new Error("Host must support timestamp APIs");
- }
- var configFileCache = createConfigFileCache(compilerHost);
+ function createSolutionBuilder(host, rootNames, defaultOptions) {
+ var hostWithWatch = host;
+ var configFileCache = createConfigFileCache(host);
var context = createBuildContext(defaultOptions);
+ var timerToBuildInvalidatedProject;
+ var reportFileChangeDetected = false;
var existingWatchersForWildcards = ts.createMap();
- var upToDateHost = {
- fileExists: function (fileName) { return compilerHost.fileExists(fileName); },
- getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); },
- getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); },
- getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); },
- setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); },
- parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); }
- };
return {
buildAllProjects: buildAllProjects,
getUpToDateStatus: getUpToDateStatus,
@@ -87997,33 +88931,54 @@ var ts;
resetBuildContext: resetBuildContext,
getBuildGraph: getBuildGraph,
invalidateProject: invalidateProject,
- buildInvalidatedProjects: buildInvalidatedProjects,
- buildDependentInvalidatedProjects: buildDependentInvalidatedProjects,
+ buildInvalidatedProject: buildInvalidatedProject,
resolveProjectName: resolveProjectName,
startWatching: startWatching
};
+ function reportStatus(message) {
+ var args = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ args[_i - 1] = arguments[_i];
+ }
+ host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)));
+ }
+ function storeErrors(proj, diagnostics) {
+ if (context.options.watch) {
+ storeErrorSummary(proj, diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length);
+ }
+ }
+ function storeErrorSummary(proj, errorCount) {
+ if (context.options.watch) {
+ context.diagnostics.setValue(proj, errorCount);
+ }
+ }
+ function reportWatchStatus(message) {
+ var args = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ args[_i - 1] = arguments[_i];
+ }
+ if (hostWithWatch.onWatchStatusChange) {
+ hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), { preserveWatchOutput: context.options.preserveWatchOutput });
+ }
+ }
function startWatching() {
- if (!system)
- throw new Error("System host must be provided if using --watch");
- if (!system.watchFile || !system.watchDirectory || !system.setTimeout)
- throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch");
var graph = getGlobalDependencyGraph();
if (!graph.buildQueue) {
// Everything is broken - we don't even know what to watch. Give up.
return;
}
- var _loop_10 = function (resolved) {
+ var _loop_9 = function (resolved) {
var cfg = configFileCache.parseConfigFile(resolved);
if (cfg) {
// Watch this file
- system.watchFile(resolved, function () {
+ hostWithWatch.watchFile(resolved, function () {
configFileCache.removeKey(resolved);
invalidateProjectAndScheduleBuilds(resolved);
});
// Update watchers for wildcard directories
if (cfg.configFileSpecs) {
ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) {
- return system.watchDirectory(dir, function () {
+ return hostWithWatch.watchDirectory(dir, function () {
invalidateProjectAndScheduleBuilds(resolved);
}, !!(flags & 1 /* Recursive */));
});
@@ -88031,7 +88986,7 @@ var ts;
// Watch input files
for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) {
var input = _a[_i];
- system.watchFile(input, function () {
+ hostWithWatch.watchFile(input, function () {
invalidateProjectAndScheduleBuilds(resolved);
});
}
@@ -88039,14 +88994,14 @@ var ts;
};
for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
var resolved = _a[_i];
- _loop_10(resolved);
- }
- function invalidateProjectAndScheduleBuilds(resolved) {
- invalidateProject(resolved);
- system.setTimeout(buildInvalidatedProjects, 100);
- system.setTimeout(buildDependentInvalidatedProjects, 3000);
+ _loop_9(resolved);
}
}
+ function invalidateProjectAndScheduleBuilds(resolved) {
+ reportFileChangeDetected = true;
+ invalidateProject(resolved);
+ scheduleBuildInvalidatedProject();
+ }
function resetBuildContext(opts) {
if (opts === void 0) { opts = defaultOptions; }
context = createBuildContext(opts);
@@ -88064,7 +89019,162 @@ var ts;
return getBuildGraph(rootNames);
}
function getUpToDateStatus(project) {
- return ts.getUpToDateStatus(upToDateHost, project);
+ if (project === undefined) {
+ return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
+ }
+ var prior = context.projectStatus.getValueOrUndefined(project.options.configFilePath);
+ if (prior !== undefined) {
+ return prior;
+ }
+ var actual = getUpToDateStatusWorker(project);
+ context.projectStatus.setValue(project.options.configFilePath, actual);
+ return actual;
+ }
+ function getUpToDateStatusWorker(project) {
+ var newestInputFileName = undefined;
+ var newestInputFileTime = minimumDate;
+ // Get timestamps of input files
+ for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
+ var inputFile = _a[_i];
+ if (!host.fileExists(inputFile)) {
+ return {
+ type: UpToDateStatusType.Unbuildable,
+ reason: inputFile + " does not exist"
+ };
+ }
+ var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
+ if (inputTime > newestInputFileTime) {
+ newestInputFileName = inputFile;
+ newestInputFileTime = inputTime;
+ }
+ }
+ // Collect the expected outputs of this project
+ var outputs = getAllProjectOutputs(project);
+ if (outputs.length === 0) {
+ return {
+ type: UpToDateStatusType.ContainerOnly
+ };
+ }
+ // Now see if all outputs are newer than the newest input
+ var oldestOutputFileName = "(none)";
+ var oldestOutputFileTime = maximumDate;
+ var newestOutputFileName = "(none)";
+ var newestOutputFileTime = minimumDate;
+ var missingOutputFileName;
+ var newestDeclarationFileContentChangedTime = minimumDate;
+ var isOutOfDateWithInputs = false;
+ for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
+ var output = outputs_1[_b];
+ // Output is missing; can stop checking
+ // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
+ if (!host.fileExists(output)) {
+ missingOutputFileName = output;
+ break;
+ }
+ var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
+ if (outputTime < oldestOutputFileTime) {
+ oldestOutputFileTime = outputTime;
+ oldestOutputFileName = output;
+ }
+ // If an output is older than the newest input, we can stop checking
+ // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
+ if (outputTime < newestInputFileTime) {
+ isOutOfDateWithInputs = true;
+ break;
+ }
+ if (outputTime > newestOutputFileTime) {
+ newestOutputFileTime = outputTime;
+ newestOutputFileName = output;
+ }
+ // Keep track of when the most recent time a .d.ts file was changed.
+ // In addition to file timestamps, we also keep track of when a .d.ts file
+ // had its file touched but not had its contents changed - this allows us
+ // to skip a downstream typecheck
+ if (isDeclarationFile(output)) {
+ var unchangedTime = context.unchangedOutputs.getValueOrUndefined(output);
+ if (unchangedTime !== undefined) {
+ newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime);
+ }
+ else {
+ var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
+ newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
+ }
+ }
+ }
+ var pseudoUpToDate = false;
+ var usesPrepend = false;
+ var upstreamChangedProject;
+ if (project.projectReferences) {
+ for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ usesPrepend = usesPrepend || !!(ref.prepend);
+ var resolvedRef = ts.resolveProjectReferencePath(host, ref);
+ var refStatus = getUpToDateStatus(configFileCache.parseConfigFile(resolvedRef));
+ // An upstream project is blocked
+ if (refStatus.type === UpToDateStatusType.Unbuildable) {
+ return {
+ type: UpToDateStatusType.UpstreamBlocked,
+ upstreamProjectName: ref.path
+ };
+ }
+ // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
+ if (refStatus.type !== UpToDateStatusType.UpToDate) {
+ return {
+ type: UpToDateStatusType.UpstreamOutOfDate,
+ upstreamProjectName: ref.path
+ };
+ }
+ // If the upstream project's newest file is older than our oldest output, we
+ // can't be out of date because of it
+ if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
+ continue;
+ }
+ // If the upstream project has only change .d.ts files, and we've built
+ // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
+ if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
+ pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
+ continue;
+ }
+ // We have an output older than an upstream output - we are out of date
+ ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: ref.path
+ };
+ }
+ }
+ if (missingOutputFileName !== undefined) {
+ return {
+ type: UpToDateStatusType.OutputMissing,
+ missingOutputFileName: missingOutputFileName
+ };
+ }
+ if (isOutOfDateWithInputs) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithSelf,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerInputFileName: newestInputFileName
+ };
+ }
+ if (usesPrepend && pseudoUpToDate) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: upstreamChangedProject
+ };
+ }
+ // Up to date
+ return {
+ type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ newestInputFileTime: newestInputFileTime,
+ newestOutputFileTime: newestOutputFileTime,
+ newestInputFileName: newestInputFileName,
+ newestOutputFileName: newestOutputFileName,
+ oldestOutputFileName: oldestOutputFileName
+ };
}
function invalidateProject(configFileName) {
var resolved = resolveProjectName(configFileName);
@@ -88076,30 +89186,44 @@ var ts;
return;
}
configFileCache.removeKey(resolved);
- context.invalidatedProjects.setValue(resolved, true);
context.projectStatus.removeKey(resolved);
- var graph = getGlobalDependencyGraph();
- if (graph) {
- queueBuildForDownstreamReferences(resolved);
+ if (context.options.watch) {
+ context.diagnostics.removeKey(resolved);
}
- // Mark all downstream projects of this one needing to be built "later"
- function queueBuildForDownstreamReferences(root) {
- var deps = graph.dependencyMap.getReferencesTo(root);
- for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) {
- var ref = deps_1[_i];
- // Can skip circular references
- if (!context.queuedProjects.hasKey(ref)) {
- context.queuedProjects.setValue(ref, true);
- queueBuildForDownstreamReferences(ref);
- }
+ context.invalidateProject(resolved, getGlobalDependencyGraph());
+ }
+ function scheduleBuildInvalidatedProject() {
+ if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
+ return;
+ }
+ if (timerToBuildInvalidatedProject) {
+ hostWithWatch.clearTimeout(timerToBuildInvalidatedProject);
+ }
+ timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250);
+ }
+ function buildInvalidatedProject() {
+ timerToBuildInvalidatedProject = undefined;
+ if (reportFileChangeDetected) {
+ reportFileChangeDetected = false;
+ reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
+ }
+ var buildProject = context.getNextInvalidatedProject();
+ buildSomeProjects(function (p) { return p === buildProject; });
+ if (context.hasPendingInvalidatedProjects()) {
+ if (!timerToBuildInvalidatedProject) {
+ scheduleBuildInvalidatedProject();
}
}
+ else {
+ reportErrorSummary();
+ }
}
- function buildInvalidatedProjects() {
- buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); });
- }
- function buildDependentInvalidatedProjects() {
- buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); });
+ function reportErrorSummary() {
+ if (context.options.watch) {
+ var errorCount_1 = 0;
+ context.diagnostics.getKeys().forEach(function (resolved) { return errorCount_1 += context.diagnostics.getValue(resolved); });
+ reportWatchStatus(errorCount_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount_1);
+ }
}
function buildSomeProjects(predicate) {
var resolvedNames = resolveProjectNames(rootNames);
@@ -88120,7 +89244,7 @@ var ts;
verboseReportProjectStatus(next, status);
if (status.type === UpToDateStatusType.UpstreamBlocked) {
if (context.options.verbose)
- buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName);
+ reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName);
continue;
}
buildSingleProject(next);
@@ -88153,7 +89277,8 @@ var ts;
if (temporaryMarks[projPath]) {
if (!inCircularContext) {
hadError = true;
- buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n"));
+ // TODO(shkamat): Account for this error
+ reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n"));
return;
}
}
@@ -88183,17 +89308,18 @@ var ts;
}
function buildSingleProject(proj) {
if (context.options.dry) {
- buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj);
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj);
return BuildResultFlags.Success;
}
if (context.options.verbose)
- buildHost.verbose(ts.Diagnostics.Building_project_0, proj);
+ reportStatus(ts.Diagnostics.Building_project_0, proj);
var resultFlags = BuildResultFlags.None;
resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
var configFile = configFileCache.parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
resultFlags |= BuildResultFlags.ConfigFileErrors;
+ storeErrorSummary(proj, 1);
context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" });
return resultFlags;
}
@@ -88203,7 +89329,7 @@ var ts;
}
var programOptions = {
projectReferences: configFile.projectReferences,
- host: compilerHost,
+ host: host,
rootNames: configFile.fileNames,
options: configFile.options
};
@@ -88214,8 +89340,9 @@ var ts;
resultFlags |= BuildResultFlags.SyntaxErrors;
for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) {
var diag = syntaxDiagnostics_1[_i];
- buildHost.errorDiagnostic(diag);
+ host.reportDiagnostic(diag);
}
+ storeErrors(proj, syntaxDiagnostics);
context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" });
return resultFlags;
}
@@ -88226,8 +89353,9 @@ var ts;
resultFlags |= BuildResultFlags.DeclarationEmitErrors;
for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) {
var diag = declDiagnostics_1[_a];
- buildHost.errorDiagnostic(diag);
+ host.reportDiagnostic(diag);
}
+ storeErrors(proj, declDiagnostics);
context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" });
return resultFlags;
}
@@ -88238,8 +89366,9 @@ var ts;
resultFlags |= BuildResultFlags.TypeErrors;
for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) {
var diag = semanticDiagnostics_1[_b];
- buildHost.errorDiagnostic(diag);
+ host.reportDiagnostic(diag);
}
+ storeErrors(proj, semanticDiagnostics);
context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" });
return resultFlags;
}
@@ -88247,17 +89376,17 @@ var ts;
var anyDtsChanged = false;
program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) {
var priorChangeTime;
- if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) {
- if (compilerHost.readFile(fileName) === content) {
+ if (!anyDtsChanged && isDeclarationFile(fileName) && host.fileExists(fileName)) {
+ if (host.readFile(fileName) === content) {
// Check for unchanged .d.ts files
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
- priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName);
+ priorChangeTime = host.getModifiedTime(fileName);
}
else {
anyDtsChanged = true;
}
}
- compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray);
+ host.writeFile(fileName, content, writeBom, onError, ts.emptyArray);
if (priorChangeTime !== undefined) {
newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
context.unchangedOutputs.setValue(fileName, priorChangeTime);
@@ -88272,20 +89401,20 @@ var ts;
}
function updateOutputTimestamps(proj) {
if (context.options.dry) {
- return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
}
if (context.options.verbose) {
- buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath);
+ reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath);
}
var now = new Date();
var outputs = getAllProjectOutputs(proj);
var priorNewestUpdateTime = minimumDate;
- for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) {
- var file = outputs_1[_i];
+ for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
+ var file = outputs_2[_i];
if (isDeclarationFile(file)) {
- priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime);
+ priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
}
- compilerHost.setModifiedTime(file, now);
+ host.setModifiedTime(file, now);
}
context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
}
@@ -88306,9 +89435,9 @@ var ts;
continue;
}
var outputs = getAllProjectOutputs(parsed);
- for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) {
- var output = outputs_2[_b];
- if (compilerHost.fileExists(output)) {
+ for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
+ var output = outputs_3[_b];
+ if (host.fileExists(output)) {
filesToDelete.push(output);
}
}
@@ -88327,38 +89456,35 @@ var ts;
function cleanAllProjects() {
var resolvedNames = getAllProjectsInScope();
if (resolvedNames === undefined) {
- buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located);
+ reportStatus(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located);
return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
var filesToDelete = getFilesToClean(resolvedNames);
if (filesToDelete === undefined) {
- buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located);
+ reportStatus(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located);
return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
if (context.options.dry) {
- buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
return ts.ExitStatus.Success;
}
- // Do this check later to allow --clean --dry to function even if the host can't delete files
- if (!compilerHost.deleteFile) {
- throw new Error("Host does not support deleting files");
- }
for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) {
var output = filesToDelete_1[_i];
- compilerHost.deleteFile(output);
+ host.deleteFile(output);
}
return ts.ExitStatus.Success;
}
function resolveProjectName(name) {
- var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name);
- if (compilerHost.fileExists(fullPath)) {
+ var fullPath = ts.resolvePath(host.getCurrentDirectory(), name);
+ if (host.fileExists(fullPath)) {
return fullPath;
}
var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json");
- if (compilerHost.fileExists(fullPathWithTsconfig)) {
+ if (host.fileExists(fullPathWithTsconfig)) {
return fullPathWithTsconfig;
}
- buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath));
+ // TODO(shkamat): right now this is accounted as 1 error in config file, but we need to do better
+ host.reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, relName(fullPath)));
return undefined;
}
function resolveProjectNames(configFileNames) {
@@ -88374,9 +89500,14 @@ var ts;
return resolvedNames;
}
function buildAllProjects() {
+ if (context.options.watch) {
+ reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode);
+ }
var graph = getGlobalDependencyGraph();
- if (graph === undefined)
+ if (graph === undefined) {
+ reportErrorSummary();
return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
+ }
var queue = graph.buildQueue;
reportBuildQueue(graph);
var anyFailed = false;
@@ -88394,7 +89525,7 @@ var ts;
// Up to date, skip
if (defaultOptions.dry) {
// In a dry build, inform the user of this fact
- buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName);
+ reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName);
}
continue;
}
@@ -88405,7 +89536,7 @@ var ts;
}
if (status.type === UpToDateStatusType.UpstreamBlocked) {
if (context.options.verbose)
- buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName);
+ reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName);
continue;
}
if (status.type === UpToDateStatusType.ContainerOnly) {
@@ -88415,6 +89546,7 @@ var ts;
var buildResult = buildSingleProject(next);
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
+ reportErrorSummary();
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
/**
@@ -88429,17 +89561,10 @@ var ts;
names.push(name);
}
if (context.options.verbose)
- buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join(""));
+ reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join(""));
}
function relName(path) {
- return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); });
- }
- function reportVerbose(message) {
- var args = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- args[_i - 1] = arguments[_i];
- }
- buildHost.verbose.apply(buildHost, [message].concat(args));
+ return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); });
}
/**
* Report the up-to-date status of a project if we're in verbose mode
@@ -88447,174 +89572,10 @@ var ts;
function verboseReportProjectStatus(configFileName, status) {
if (!context.options.verbose)
return;
- return formatUpToDateStatus(configFileName, status, relName, reportVerbose);
+ return formatUpToDateStatus(configFileName, status, relName, reportStatus);
}
}
ts.createSolutionBuilder = createSolutionBuilder;
- /**
- * Gets the UpToDateStatus for a project
- */
- function getUpToDateStatus(host, project) {
- if (project === undefined) {
- return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
- }
- var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined;
- if (prior !== undefined) {
- return prior;
- }
- var actual = getUpToDateStatusWorker(host, project);
- if (host.setLastStatus) {
- host.setLastStatus(project.options.configFilePath, actual);
- }
- return actual;
- }
- ts.getUpToDateStatus = getUpToDateStatus;
- function getUpToDateStatusWorker(host, project) {
- var newestInputFileName = undefined;
- var newestInputFileTime = minimumDate;
- // Get timestamps of input files
- for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
- var inputFile = _a[_i];
- if (!host.fileExists(inputFile)) {
- return {
- type: UpToDateStatusType.Unbuildable,
- reason: inputFile + " does not exist"
- };
- }
- var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
- if (inputTime > newestInputFileTime) {
- newestInputFileName = inputFile;
- newestInputFileTime = inputTime;
- }
- }
- // Collect the expected outputs of this project
- var outputs = getAllProjectOutputs(project);
- if (outputs.length === 0) {
- return {
- type: UpToDateStatusType.ContainerOnly
- };
- }
- // Now see if all outputs are newer than the newest input
- var oldestOutputFileName = "(none)";
- var oldestOutputFileTime = maximumDate;
- var newestOutputFileName = "(none)";
- var newestOutputFileTime = minimumDate;
- var missingOutputFileName;
- var newestDeclarationFileContentChangedTime = minimumDate;
- var isOutOfDateWithInputs = false;
- for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
- var output = outputs_3[_b];
- // Output is missing; can stop checking
- // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
- if (!host.fileExists(output)) {
- missingOutputFileName = output;
- break;
- }
- var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
- if (outputTime < oldestOutputFileTime) {
- oldestOutputFileTime = outputTime;
- oldestOutputFileName = output;
- }
- // If an output is older than the newest input, we can stop checking
- // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
- if (outputTime < newestInputFileTime) {
- isOutOfDateWithInputs = true;
- break;
- }
- if (outputTime > newestOutputFileTime) {
- newestOutputFileTime = outputTime;
- newestOutputFileName = output;
- }
- // Keep track of when the most recent time a .d.ts file was changed.
- // In addition to file timestamps, we also keep track of when a .d.ts file
- // had its file touched but not had its contents changed - this allows us
- // to skip a downstream typecheck
- if (isDeclarationFile(output)) {
- var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined;
- if (unchangedTime !== undefined) {
- newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime);
- }
- else {
- var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
- newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
- }
- }
- }
- var pseudoUpToDate = false;
- var usesPrepend = false;
- var upstreamChangedProject;
- if (project.projectReferences && host.parseConfigFile) {
- for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
- var ref = _d[_c];
- usesPrepend = usesPrepend || !!(ref.prepend);
- var resolvedRef = ts.resolveProjectReferencePath(host, ref);
- var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef));
- // An upstream project is blocked
- if (refStatus.type === UpToDateStatusType.Unbuildable) {
- return {
- type: UpToDateStatusType.UpstreamBlocked,
- upstreamProjectName: ref.path
- };
- }
- // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
- if (refStatus.type !== UpToDateStatusType.UpToDate) {
- return {
- type: UpToDateStatusType.UpstreamOutOfDate,
- upstreamProjectName: ref.path
- };
- }
- // If the upstream project's newest file is older than our oldest output, we
- // can't be out of date because of it
- if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
- continue;
- }
- // If the upstream project has only change .d.ts files, and we've built
- // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
- if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
- pseudoUpToDate = true;
- upstreamChangedProject = ref.path;
- continue;
- }
- // We have an output older than an upstream output - we are out of date
- ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
- return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: oldestOutputFileName,
- newerProjectName: ref.path
- };
- }
- }
- if (missingOutputFileName !== undefined) {
- return {
- type: UpToDateStatusType.OutputMissing,
- missingOutputFileName: missingOutputFileName
- };
- }
- if (isOutOfDateWithInputs) {
- return {
- type: UpToDateStatusType.OutOfDateWithSelf,
- outOfDateOutputFileName: oldestOutputFileName,
- newerInputFileName: newestInputFileName
- };
- }
- if (usesPrepend && pseudoUpToDate) {
- return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: oldestOutputFileName,
- newerProjectName: upstreamChangedProject
- };
- }
- // Up to date
- return {
- type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate,
- newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
- newestInputFileTime: newestInputFileTime,
- newestOutputFileTime: newestOutputFileTime,
- newestInputFileName: newestInputFileName,
- newestOutputFileName: newestOutputFileName,
- oldestOutputFileName: oldestOutputFileName
- };
- }
function getAllProjectOutputs(project) {
if (project.options.outFile) {
return getOutFileOutputs(project);
@@ -88715,8 +89676,8 @@ var ts;
(function (JsTyping) {
/* @internal */
function isTypingUpToDate(cachedTyping, availableTypingVersions) {
- var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
- return !availableVersion.greaterThan(cachedTyping.version);
+ var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
+ return availableVersion.compareTo(cachedTyping.version) <= 0;
}
JsTyping.isTypingUpToDate = isTypingUpToDate;
/* @internal */
@@ -89005,71 +89966,6 @@ var ts;
JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
})(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- function stringToInt(str) {
- var n = parseInt(str, 10);
- if (isNaN(n)) {
- throw new Error("Error in parseInt(" + JSON.stringify(str) + ")");
- }
- return n;
- }
- var isPrereleaseRegex = /^(.*)-next.\d+/;
- var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/;
- var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/;
- var Semver = /** @class */ (function () {
- function Semver(major, minor, patch,
- /**
- * If true, this is `major.minor.0-next.patch`.
- * If false, this is `major.minor.patch`.
- */
- isPrerelease) {
- this.major = major;
- this.minor = minor;
- this.patch = patch;
- this.isPrerelease = isPrerelease;
- }
- Semver.parse = function (semver) {
- var isPrerelease = isPrereleaseRegex.test(semver);
- var result = Semver.tryParse(semver, isPrerelease);
- if (!result) {
- throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")");
- }
- return result;
- };
- Semver.fromRaw = function (_a) {
- var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease;
- return new Semver(major, minor, patch, isPrerelease);
- };
- // This must parse the output of `versionString`.
- Semver.tryParse = function (semver, isPrerelease) {
- // Per the semver spec :
- // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes."
- var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex;
- var match = rgx.exec(semver);
- return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined;
- };
- Object.defineProperty(Semver.prototype, "versionString", {
- get: function () {
- return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch;
- },
- enumerable: true,
- configurable: true
- });
- Semver.prototype.equals = function (sem) {
- return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease;
- };
- Semver.prototype.greaterThan = function (sem) {
- return this.major > sem.major || this.major === sem.major
- && (this.minor > sem.minor || this.minor === sem.minor
- && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease
- && this.patch > sem.patch));
- };
- return Semver;
- }());
- ts.Semver = Semver;
-})(ts || (ts = {}));
//# sourceMappingURL=jsTyping.js.map
"use strict";
var ts;
@@ -89277,8 +90173,10 @@ var ts;
}
var info = ts.getProperty(npmLock.dependencies, key);
var version_1 = info && info.version;
- var semver = ts.Semver.parse(version_1); // TODO: GH#18217
- var newTyping = { typingLocation: typingFile, version: semver };
+ if (!version_1) {
+ continue;
+ }
+ var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
this.packageNameToTypingLocation.set(packageName, newTyping);
}
}
@@ -89380,7 +90278,7 @@ var ts;
}
// packageName is guaranteed to exist in typesRegistry by filterTypings
var distTags = _this.typesRegistry.get(packageName);
- var newVersion = ts.Semver.parse(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
+ var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
var newTyping = { typingLocation: typingFile, version: newVersion };
_this.packageNameToTypingLocation.set(packageName, newTyping);
installedTypingFiles.push(typingFile);
diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json
index aaf6a7101a8..23d0bae7b27 100644
--- a/lib/zh-cn/diagnosticMessages.generated.json
+++ b/lib/zh-cn/diagnosticMessages.generated.json
@@ -68,7 +68,7 @@
"A_rest_parameter_cannot_have_an_initializer_1048": "rest 参数不能具有初始化表达式。",
"A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 参数必须是参数列表中的最后一个参数。",
"A_rest_parameter_must_be_of_an_array_type_2370": "rest 参数必须是数组类型。",
- "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式可能不具有尾随逗号。",
+ "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式不可带尾随逗号。",
"A_return_statement_can_only_be_used_within_a_function_body_1108": "\"return\" 语句只能在函数体中使用。",
"A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "一系列条目,这些条目将重新映射导入内容,以查找与 \"baseUrl\" 有关的位置。",
"A_set_accessor_cannot_have_a_return_type_annotation_1095": "\"set\" 访问器不能具有返回类型批注。",
@@ -161,7 +161,7 @@
"An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引签名参数不能具有可访问性修饰符。",
"An_index_signature_parameter_cannot_have_an_initializer_1020": "索引签名参数不能具有初始化表达式。",
"An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。",
- "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改而编写“[{0}: {1}]:{2}”。",
+ "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改为编写“[{0}: {1}]:{2}”。",
"An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引签名参数类型不能为联合类型。请考虑改用映射的对象类型。",
"An_index_signature_parameter_type_must_be_string_or_number_1023": "索引签名参数类型必须为 \"string\" 或 \"number\"。",
"An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。",
@@ -628,7 +628,7 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。",
- "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。",
+ "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "在没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。",
"Options_0_and_1_cannot_be_combined_6370": "选项“{0}”与“{1}”不能组合在一起。",
"Options_Colon_6027": "选项:",
"Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。",