From b23671b96b1da04491d04e474cef341ae31c03d6 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Thu, 24 May 2018 13:50:41 -0700 Subject: [PATCH] Update LKG --- lib/tsc.js | 191 +++++++----- lib/tsserver.js | 525 +++++++++++++++++++-------------- lib/tsserverlibrary.d.ts | 24 +- lib/tsserverlibrary.js | 573 +++++++++++++++++++++--------------- lib/typescript.d.ts | 19 +- lib/typescript.js | 555 +++++++++++++++++++--------------- lib/typescriptServices.d.ts | 19 +- lib/typescriptServices.js | 555 +++++++++++++++++++--------------- lib/typingsInstaller.js | 35 ++- 9 files changed, 1487 insertions(+), 1009 deletions(-) diff --git a/lib/tsc.js b/lib/tsc.js index 11fd8845d40..a657eede679 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -974,15 +974,6 @@ var ts; return to; } ts.addRange = addRange; - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; function pushIfUnique(array, toAdd, equalityComparer) { if (contains(array, toAdd, equalityComparer)) { return false; @@ -1729,6 +1720,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -4198,7 +4197,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -4554,7 +4553,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -6602,6 +6601,19 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { if (text.charCodeAt(commentPos + 1) === 47 && commentPos + 2 < commentEnd && @@ -12428,6 +12440,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -18323,7 +18336,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217) { addAntecedent(postStatementLabel, currentFlow); @@ -18864,6 +18877,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -19495,13 +19518,13 @@ var ts; (node.kind === 237 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304) && - (node.kind !== 213 || - ts.getCombinedNodeFlags(node.declarationList) & 3 || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -23400,7 +23423,7 @@ var ts; } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -23423,13 +23446,18 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { return false; } @@ -23489,7 +23517,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { return { accessibility: 0 }; @@ -23523,6 +23551,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -23806,8 +23837,9 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8), undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928, false) : ts.createIdentifier("?"); - return ts.createTypeReferenceNode(name, undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); @@ -24274,7 +24306,7 @@ var ts; return accessibleSymbolChain; } if (endOfChain || - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && !(symbol.flags & (2048 | 4096))) { return [symbol]; } @@ -28790,7 +28822,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 8388608 ? type.regularType : type; + return type.flags & 96 && type.flags & 8388608 ? type.regularType : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { var qualifier = typeof value === "number" ? "#" : "@"; @@ -31631,10 +31665,12 @@ var ts; } function getCovariantInference(inference, context, signature) { var candidates = widenObjectLiteralCandidates(inference.candidates); - var widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; var unwidenedType = context.flags & 1 || inference.priority & 28 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); @@ -33580,6 +33616,22 @@ var ts; return getContextualType(attribute.parent); } } + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9: + case 8: + case 13: + case 101: + case 86: + case 95: + case 71: + return true; + case 184: + case 190: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); @@ -33593,8 +33645,8 @@ var ts; continue; if (prop.kind !== 269) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -37424,14 +37476,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 && - constraintDeclaration.operator === 128; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216) { @@ -37440,11 +37484,9 @@ var ts; } if (contextualType.flags & 7372800) { var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 | 64 | 1024) || - constraint.flags & 2 && maybeTypeOfKind(candidateType, 32) || - constraint.flags & 4 && maybeTypeOfKind(candidateType, 64) || - constraint.flags & 8 && maybeTypeOfKind(candidateType, 128) || - constraint.flags & 512 && maybeTypeOfKind(candidateType, 1024) || + return maybeTypeOfKind(constraint, 2) && maybeTypeOfKind(candidateType, 32) || + maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 64) || + maybeTypeOfKind(constraint, 512) && maybeTypeOfKind(candidateType, 1024) || isLiteralOfContextualType(candidateType, constraint); } return contextualType.flags & (32 | 524288) && maybeTypeOfKind(candidateType, 32) || @@ -42003,7 +42045,7 @@ var ts; } } if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -45682,6 +45724,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -47989,7 +48033,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function liftToBlock(nodes) { @@ -49014,7 +49058,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ @@ -49604,7 +49648,8 @@ var ts; return serializedUnion || ts.createVoidZero(); } function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -49630,8 +49675,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } function serializeEntityNameAsExpression(node, useFallback) { @@ -49900,7 +49946,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); @@ -50045,7 +50091,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -50611,7 +50657,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); if (languageVersion >= 2) { @@ -51118,7 +51164,7 @@ var ts; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { @@ -51144,7 +51190,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -52009,7 +52055,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0, 0); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -52178,7 +52224,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); ts.setEmitFlags(block, 1536); return block; @@ -52241,7 +52287,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, false); } @@ -52643,7 +52689,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, false); if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { multiLine = true; @@ -53048,7 +53094,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, true); } if (ts.isBlock(loopBody)) { @@ -54042,7 +54088,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); inGeneratorFunctionBody = savedInGeneratorFunctionBody; inStatementContainingYield = savedInStatementContainingYield; @@ -55508,7 +55554,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); @@ -55623,7 +55669,7 @@ var ts; } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); @@ -56427,7 +56473,7 @@ var ts; ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); ts.addRange(statements, hoistedStatements); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -63106,8 +63152,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -63760,11 +63805,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } function shouldReportDiagnostic(diagnostic) { diff --git a/lib/tsserver.js b/lib/tsserver.js index b54723f6129..e91c87339e4 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -2187,15 +2187,6 @@ var ts; return to; } ts.addRange = addRange; - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; function pushIfUnique(array, toAdd, equalityComparer) { if (contains(array, toAdd, equalityComparer)) { return false; @@ -2942,6 +2933,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -5430,7 +5429,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -5786,7 +5785,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -7834,6 +7833,19 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { if (text.charCodeAt(commentPos + 1) === 47 && commentPos + 2 < commentEnd && @@ -13695,6 +13707,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -19657,7 +19670,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217) { addAntecedent(postStatementLabel, currentFlow); @@ -20203,6 +20216,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -20834,13 +20857,13 @@ var ts; (node.kind === 237 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304) && - (node.kind !== 213 || - ts.getCombinedNodeFlags(node.declarationList) & 3 || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -24843,7 +24866,7 @@ var ts; } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -24866,13 +24889,18 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { return false; } @@ -24932,7 +24960,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { return { accessibility: 0 }; @@ -24966,6 +24994,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -25249,8 +25280,9 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8), undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928, false) : ts.createIdentifier("?"); - return ts.createTypeReferenceNode(name, undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); @@ -25717,7 +25749,7 @@ var ts; return accessibleSymbolChain; } if (endOfChain || - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && !(symbol.flags & (2048 | 4096))) { return [symbol]; } @@ -30233,7 +30265,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 8388608 ? type.regularType : type; + return type.flags & 96 && type.flags & 8388608 ? type.regularType : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { var qualifier = typeof value === "number" ? "#" : "@"; @@ -33074,10 +33108,12 @@ var ts; } function getCovariantInference(inference, context, signature) { var candidates = widenObjectLiteralCandidates(inference.candidates); - var widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; var unwidenedType = context.flags & 1 || inference.priority & 28 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); @@ -35023,6 +35059,22 @@ var ts; return getContextualType(attribute.parent); } } + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9: + case 8: + case 13: + case 101: + case 86: + case 95: + case 71: + return true; + case 184: + case 190: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); @@ -35036,8 +35088,8 @@ var ts; continue; if (prop.kind !== 269) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -38867,14 +38919,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 && - constraintDeclaration.operator === 128; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216) { @@ -38883,11 +38927,9 @@ var ts; } if (contextualType.flags & 7372800) { var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 | 64 | 1024) || - constraint.flags & 2 && maybeTypeOfKind(candidateType, 32) || - constraint.flags & 4 && maybeTypeOfKind(candidateType, 64) || - constraint.flags & 8 && maybeTypeOfKind(candidateType, 128) || - constraint.flags & 512 && maybeTypeOfKind(candidateType, 1024) || + return maybeTypeOfKind(constraint, 2) && maybeTypeOfKind(candidateType, 32) || + maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 64) || + maybeTypeOfKind(constraint, 512) && maybeTypeOfKind(candidateType, 1024) || isLiteralOfContextualType(candidateType, constraint); } return contextualType.flags & (32 | 524288) && maybeTypeOfKind(candidateType, 32) || @@ -43460,7 +43502,7 @@ var ts; } } if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -47146,6 +47188,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -49460,7 +49504,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function liftToBlock(nodes) { @@ -50512,7 +50556,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ @@ -51102,7 +51146,8 @@ var ts; return serializedUnion || ts.createVoidZero(); } function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -51128,8 +51173,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } function serializeEntityNameAsExpression(node, useFallback) { @@ -51398,7 +51444,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); @@ -51543,7 +51589,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -52113,7 +52159,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); if (languageVersion >= 2) { @@ -52624,7 +52670,7 @@ var ts; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { @@ -52650,7 +52696,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -53584,7 +53630,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0, 0); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -53753,7 +53799,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); ts.setEmitFlags(block, 1536); return block; @@ -53816,7 +53862,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, false); } @@ -54218,7 +54264,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, false); if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { multiLine = true; @@ -54623,7 +54669,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, true); } if (ts.isBlock(loopBody)) { @@ -55662,7 +55708,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); inGeneratorFunctionBody = savedInGeneratorFunctionBody; inStatementContainingYield = savedInStatementContainingYield; @@ -57128,7 +57174,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); @@ -57243,7 +57289,7 @@ var ts; } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); @@ -58047,7 +58093,7 @@ var ts; ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); ts.addRange(statements, hoistedStatements); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -64751,8 +64797,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -65410,11 +65455,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } function shouldReportDiagnostic(diagnostic) { @@ -71208,14 +71261,14 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier) { + function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { return ts.createImportDeclaration(undefined, undefined, defaultImport || namedImports ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) - : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier, preferences.quotePreference === "single") : moduleSpecifier); } ts.makeImport = makeImport; function symbolNameNoDefault(symbol) { @@ -74642,6 +74695,10 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); @@ -74662,8 +74719,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -74694,23 +74750,40 @@ var ts; var bucket = getBucketForCompilationSettings(key, true); var entry = bucket.get(path); var scriptTarget = scriptKind === 6 ? 100 : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } if (!entry) { var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, false, scriptKind); + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } else { if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } if (acquiring) { entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -74728,6 +74801,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -74735,11 +74815,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); var ts; (function (ts) { @@ -75183,6 +75264,9 @@ var ts; else if (ts.isBinaryExpression(decl)) { return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } function getExportNode(parent, node) { @@ -76356,6 +76440,67 @@ var ts; })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); var ts; +(function (ts) { + function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { + var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; + var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); + if (newPath !== undefined) { + var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); + changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); + } + } + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + var configFile = program.getCompilerOptions().configFile; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); + if (oldFile) { + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + } + } + function isRef(toUpdate) { + return "fileName" in toUpdate; + } + function getImportsToUpdate(program, oldFilePath, host) { + var result = []; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var ref = _c[_b]; + if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { + result.push({ sourceFile: sourceFile, toUpdate: ref }); + } + } + for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { + var importStringLiteral = _e[_d]; + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { + result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); + } + } + } + return result; + } + function getPathUpdater(oldFilePath, newFilePath, host) { + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + return function (oldPath) { + if (!ts.pathIsRelative(oldPath)) + return; + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + }; + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } +})(ts || (ts = {})); +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -77881,7 +78026,7 @@ var ts; function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -77915,7 +78060,7 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { @@ -78065,70 +78210,6 @@ var ts; })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); var ts; -(function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); - return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { - var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; - var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); - if (newPath !== undefined) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } - }); - } - ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); - } - } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var checker = program.getTypeChecker(); - var result = []; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (!program.getSourceFileFromReference(sourceFile, ref) && ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - if (checker.getSymbolAtLocation(importStringLiteral)) - continue; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } - } - return result; - } - function getPathUpdater(oldFilePath, newFilePath, host) { - var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; - } - function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); - } -})(ts || (ts = {})); -var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { @@ -79387,6 +79468,7 @@ var ts; } } } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; @@ -82199,8 +82281,9 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0; + switch (parent.kind) { case 215: case 234: case 204: @@ -82222,7 +82305,6 @@ var ts; case 186: case 187: case 213: - case 231: case 248: case 224: case 200: @@ -82245,22 +82327,14 @@ var ts; case 246: case 251: case 247: - case 269: case 151: return true; - } - return false; - } - function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { - var childKind = child ? child.kind : 0; - switch (parent.kind) { case 231: case 269: - case 183: if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183) { return rangeIsOnOneLine(sourceFile, child); } - break; + return true; case 217: case 218: case 220: @@ -82284,6 +82358,11 @@ var ts; return childKind !== 257; case 258: return childKind !== 260; + case 169: + case 168: + if (childKind === 165) { + return false; + } } return indentByDefault; } @@ -82307,7 +82386,7 @@ var ts; } function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(settings, parent, child, sourceFile, false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; @@ -82782,7 +82861,7 @@ var ts; var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); } return changes; }; @@ -82819,8 +82898,11 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter) { - var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; @@ -83525,20 +83607,20 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); } } }); return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -83548,7 +83630,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, undefined, moduleSpecifier, preferences)); break; case 186: if (ts.isRequireCall(importNode, false)) { @@ -83558,14 +83640,14 @@ var ts; } } } - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -83599,17 +83681,17 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { switch (statement.kind) { case 213: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); return false; case 215: { var expression = statement.expression; switch (expression.kind) { case 186: { if (ts.isRequireCall(expression, true)) { - changes.replaceNode(sourceFile, statement, ts.makeImport(undefined, undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(undefined, undefined, expression.arguments[0], preferences)); } return false; } @@ -83623,7 +83705,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -83635,11 +83717,11 @@ var ts; } else if (ts.isRequireCall(initializer, true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); } } return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); @@ -83648,18 +83730,18 @@ var ts; changes.replaceNodeWithNodes(sourceFile, statement, newNodes); } } - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { switch (name.kind) { case 179: case 180: { var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), + makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), makeConst(undefined, name, ts.createIdentifier(tmp)), ]; } case 71: - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; default: ts.Debug.assertNever(name); } @@ -83775,7 +83857,7 @@ var ts; return makeConst(modifiers, ts.createIdentifier(name), exported); } } - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { switch (name.kind) { case 179: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { @@ -83784,23 +83866,23 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [ts.makeImport(undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(undefined, importSpecifiers, moduleSpecifier, preferences)]; } } case 180: { var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier, preferences), makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); default: ts.Debug.assertNever(name); } } - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { var nameSymbol = checker.getSymbolAtLocation(name); var namedBindingsNames = ts.createMap(); var needDefaultImport = false; @@ -83831,7 +83913,7 @@ var ts; if (!namedBindings) { needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; } function makeUniqueName(name, identifiers) { while (identifiers.original.has(name) || identifiers.additional.has(name)) { @@ -83867,10 +83949,10 @@ var ts; function classExpressionToDeclaration(name, additionalModifiers, cls) { return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier) { + function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier) - : ts.makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier, preferences) + : ts.makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -86146,7 +86228,7 @@ var ts; var namespace = ts.getNamespaceDeclarationNode(node); var opts = context.program.getCompilerOptions(); var variations = []; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, undefined, node.moduleSpecifier, context.preferences))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(undefined, undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)))); } @@ -86579,14 +86661,14 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start); if (info) - doChange(changes, diag.file, info); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { @@ -86602,8 +86684,8 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, undefined, info.moduleSpecifier, preferences)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -88088,7 +88170,7 @@ var ts; var refactorName = "Move to a new file"; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { - if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; @@ -88096,46 +88178,50 @@ var ts; getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === refactorName); var statements = ts.Debug.assertDefined(getStatementsToMove(context)); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - function getFirstAndLastStatementToMove(context) { + function getRangeToMove(context) { var file = context.file; var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); var statements = file.statements; var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); if (startNodeIndex === -1) return undefined; - if (range.pos > statements[startNodeIndex].getStart(file)) + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return [statements[startNodeIndex]]; + } + if (range.pos > startStatement.getStart(file)) return undefined; var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); } - function doChange(oldFile, program, toMove, changes, host) { + function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); var extension = ts.extensionFromPath(oldFile.fileName); var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; - changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); } function getStatementsToMove(context) { - var statements = context.file.statements; - var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; var all = []; var ranges = []; - var rangeToMove = statements.slice(first, afterLast); ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { for (var i = start; i < afterEnd; i++) all.push(rangeToMove[i]); ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); }); - return { all: all, ranges: ranges }; + return all.length === 0 ? undefined : { all: all, ranges: ranges }; } function isPureImport(node) { switch (node.kind) { @@ -88163,21 +88249,21 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { deleteMovedStatements(oldFile, toMove.ranges, changes); return toMove.all; } var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, preferences); if (importsFromNewFile) { changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); } function deleteMovedStatements(sourceFile, moved, changes) { for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { @@ -88247,7 +88333,7 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { @@ -88258,13 +88344,13 @@ var ts; imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { path = ts.ensurePathIsNonModuleName(path); if (useEs6Imports) { var specifiers = imports.map(function (i) { return ts.createImportSpecifier(undefined, ts.createIdentifier(i)); }); - return ts.makeImportIfNecessary(defaultImport, specifiers, path); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, preferences); } else { ts.Debug.assert(!defaultImport); @@ -88363,7 +88449,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -88394,7 +88480,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -91333,7 +91419,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = (function (_super) { @@ -93869,7 +93956,7 @@ var ts; if (this.host.realpath) { this.realpathToScriptInfos = ts.createMultiMap(); } - this.currentDirectory = this.host.getCurrentDirectory(); + this.currentDirectory = server.toNormalizedPath(this.host.getCurrentDirectory()); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation && ts.ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)); @@ -93888,7 +93975,7 @@ var ts; hostInfo: "Unknown host", extraFileExtensions: [] }; - this.documentRegistry = ts.createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.currentDirectory); + this.documentRegistry = ts.createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this); var watchLogLevel = this.logger.hasLevel(server.LogLevel.verbose) ? ts.WatchLogLevel.Verbose : this.logger.loggingEnabled() ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None; var log = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return _this.logger.info(s); }) : ts.noop; @@ -93903,6 +93990,15 @@ var ts; ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); }; + ProjectService.prototype.setDocument = function (key, path, sourceFile) { + var info = this.getScriptInfoForPath(path); + ts.Debug.assert(!!info); + info.cacheSourceFile = { key: key, sourceFile: sourceFile }; + }; + ProjectService.prototype.getDocument = function (key, path) { + var info = this.getScriptInfoForPath(path); + return info && info.cacheSourceFile && info.cacheSourceFile.key === key && info.cacheSourceFile.sourceFile; + }; ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { this.ensureProjectStructuresUptoDate(); }; @@ -95832,6 +95928,7 @@ var ts; this.logger = opts.logger; this.canUseEvents = opts.canUseEvents; this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate; var throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = this.canUseEvents ? opts.eventHandler || (function (event) { return _this.defaultEventHandler(event); }) @@ -95903,7 +96000,7 @@ var ts; var _this = this; this.projectService.logger.info("got projects updated in background, updating diagnostics for " + openFiles); if (openFiles.length) { - if (!this.suppressDiagnosticEvents) { + if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { var checkList_1 = this.createCheckList(openFiles); this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, true); }); } @@ -98303,6 +98400,7 @@ var ts; canUseEvents: true, suppressDiagnosticEvents: suppressDiagnosticEvents, syntaxOnly: syntaxOnly, + noGetErrOnBackgroundUpdate: noGetErrOnBackgroundUpdate, globalPlugins: globalPlugins, pluginProbeLocations: pluginProbeLocations, allowLocalPluginLoads: allowLocalPluginLoads, @@ -98660,6 +98758,7 @@ var ts; var suppressDiagnosticEvents = server.hasArgument("--suppressDiagnosticEvents"); var syntaxOnly = server.hasArgument("--syntaxOnly"); var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry); + var noGetErrOnBackgroundUpdate = server.hasArgument("--noGetErrOnBackgroundUpdate"); logger.info("Starting TS Server"); logger.info("Version: " + ts.version); logger.info("Arguments: " + process.argv.join(" ")); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index cbf39a2a48f..e5ac29026ce 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1734,9 +1734,10 @@ declare namespace ts { emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. @@ -2359,6 +2360,11 @@ declare namespace ts { code: number; source?: string; } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; + } enum DiagnosticCategory { Warning = 0, Error = 1, @@ -2754,7 +2760,7 @@ declare namespace ts { /** Gets the transformed source files. */ transformed: T[]; /** Gets diagnostics for the transformation. */ - diagnostics?: Diagnostic[]; + diagnostics?: DiagnosticWithLocation[]; /** * Gets a substitute for a node, if one is available; otherwise, returns the original node. * @@ -2960,7 +2966,7 @@ declare namespace ts { } declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): Diagnostic[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -4497,9 +4503,10 @@ declare namespace ts { } interface LanguageService { cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(fileName: string): Diagnostic[]; - getSuggestionDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. @@ -8127,7 +8134,6 @@ declare namespace ts.server { syntaxOnly?: boolean; } class ProjectService { - private readonly documentRegistry; /** * Container of all known scripts */ @@ -8176,7 +8182,7 @@ declare namespace ts.server { private safelist; private legacySafelist; private pendingProjectUpdates; - readonly currentDirectory: string; + readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; readonly host: ServerHost; readonly logger: Logger; @@ -8391,6 +8397,7 @@ declare namespace ts.server { suppressDiagnosticEvents?: boolean; syntaxOnly?: boolean; throttleWaitMilliseconds?: number; + noGetErrOnBackgroundUpdate?: boolean; globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; @@ -8410,6 +8417,7 @@ declare namespace ts.server { protected canUseEvents: boolean; private suppressDiagnosticEvents?; private eventHandler; + private readonly noGetErrOnBackgroundUpdate?; constructor(opts: SessionOptions); private sendRequestCompletedEvent; private defaultEventHandler; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 22e5f359e1f..8beac9ebb61 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -2539,23 +2539,6 @@ var ts; return to; } ts.addRange = addRange; - /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - */ - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; /** * @return Whether the value was added. */ @@ -3446,6 +3429,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -6274,7 +6265,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -6630,7 +6621,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -8898,6 +8889,27 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Appends a range of value to begin of an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; /** * Determine if the given comment is a triple-slash * @@ -15606,6 +15618,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -22879,7 +22892,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -23509,6 +23522,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -24257,22 +24280,22 @@ var ts; (node.kind === 237 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304 /* Ambient */) && - (node.kind !== 213 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -28901,7 +28924,7 @@ var ts; // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -28929,6 +28952,11 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } @@ -28936,7 +28964,7 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; @@ -29010,7 +29038,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // Any meaning of a module symbol is always accessible via an `import` type return { accessibility: 0 /* Accessible */ @@ -29061,6 +29089,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -29356,9 +29387,10 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928 /* 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); @@ -29860,7 +29892,7 @@ var ts; // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; @@ -35006,7 +35038,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -38282,10 +38316,12 @@ var ts; // all inferences were made to top-level occurrences of the type parameter, and // the type parameter has no constraint or its constraint includes no primitive or literal types, and // the type parameter was fixed during inference or does not occur at top-level in the return type. - var widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + 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. @@ -40592,6 +40628,25 @@ var ts; return getContextualType(attribute.parent); } } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 71 /* Identifier */: + return true; + case 184 /* PropertyAccessExpression */: + case 190 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { @@ -40608,8 +40663,8 @@ var ts; continue; if (prop.kind !== 269 /* PropertyAssignment */) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -45357,14 +45412,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768 /* TypeParameter */) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216 /* UnionOrIntersection */) { @@ -45376,11 +45423,9 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */ | 64 /* NumberLiteral */ | 1024 /* UniqueESSymbol */) || - constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 2 /* String */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + maybeTypeOfKind(constraint, 4 /* Number */) && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 512 /* ESSymbol */) && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a @@ -50817,7 +50862,7 @@ var ts; } // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -54663,6 +54708,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -57550,7 +57597,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -58984,7 +59031,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -60071,7 +60118,8 @@ var ts; * @param node The type reference node. */ function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -60097,8 +60145,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } /** @@ -60607,7 +60656,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -60848,7 +60897,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -61657,7 +61706,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -62256,7 +62305,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -62284,7 +62333,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -63377,7 +63426,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -63631,7 +63680,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -63744,7 +63793,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -64387,7 +64436,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { @@ -64968,7 +65017,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -66643,7 +66692,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -68879,7 +68928,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -69102,7 +69151,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -70371,7 +70420,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -78224,8 +78273,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -79031,11 +79079,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } /** @@ -85690,16 +85746,16 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier) { + function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) - : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier, preferences.quotePreference === "single") : moduleSpecifier); } ts.makeImport = makeImport; function symbolNameNoDefault(symbol) { @@ -89748,6 +89804,11 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. @@ -89770,8 +89831,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -89802,13 +89862,26 @@ var ts; var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } 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); + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } @@ -89818,6 +89891,9 @@ var ts; // return it as is. if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } // If we're acquiring, then this is the first time this LS is asking for this document. // Increase our ref count so we know there's another LS using the document. If we're @@ -89828,6 +89904,7 @@ var ts; entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -89845,6 +89922,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -89852,11 +89936,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -90359,6 +90444,9 @@ var ts; else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } // If a reference is a class expression, the exported node would be its parent. @@ -91802,6 +91890,70 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { + var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; + var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); + if (newPath !== undefined) { + var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); + changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); + } + } + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + var configFile = program.getCompilerOptions().configFile; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); + if (oldFile) { + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + } + } + function isRef(toUpdate) { + return "fileName" in toUpdate; + } + function getImportsToUpdate(program, oldFilePath, host) { + var result = []; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var ref = _c[_b]; + if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { + result.push({ sourceFile: sourceFile, toUpdate: ref }); + } + } + for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { + var importStringLiteral = _e[_d]; + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + // We may or may not have picked up on the file being renamed, so maybe successfully resolved to oldFilePath, or maybe that's in failedLookupLocations + if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { + result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); + } + } + } + return result; + } + function getPathUpdater(oldFilePath, newFilePath, host) { + // Get the relative path from old to new location, and append it on to the end of imports and normalize. + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + return function (oldPath) { + if (!ts.pathIsRelative(oldPath)) + return; + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + }; + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -93582,7 +93734,7 @@ var ts; function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -93620,8 +93772,8 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - // The JSX factory symbol is always used. - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { @@ -93801,73 +93953,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); - return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { - var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; - var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); - if (newPath !== undefined) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } - }); - } - ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); - } - } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var checker = program.getTypeChecker(); - var result = []; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (!program.getSourceFileFromReference(sourceFile, ref) && ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - // If it resolved to something already, ignore. - if (checker.getSymbolAtLocation(importStringLiteral)) - continue; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } - } - return result; - } - function getPathUpdater(oldFilePath, newFilePath, host) { - // Get the relative path from old to new location, and append it on to the end of imports and normalize. - var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; - } - function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); - } -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { @@ -95430,6 +95515,7 @@ var ts; } } } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; @@ -98702,8 +98788,9 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { case 215 /* ExpressionStatement */: case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: @@ -98725,7 +98812,6 @@ var ts; case 186 /* CallExpression */: case 187 /* NewExpression */: case 213 /* VariableStatement */: - case 231 /* VariableDeclaration */: case 248 /* ExportAssignment */: case 224 /* ReturnStatement */: case 200 /* ConditionalExpression */: @@ -98748,22 +98834,14 @@ var ts; case 246 /* NamedImports */: case 251 /* ExportSpecifier */: case 247 /* ImportSpecifier */: - case 269 /* PropertyAssignment */: case 151 /* PropertyDeclaration */: return true; - } - return false; - } - function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { - var childKind = child ? child.kind : 0 /* Unknown */; - switch (parent.kind) { case 231 /* VariableDeclaration */: case 269 /* PropertyAssignment */: - case 183 /* ObjectLiteralExpression */: if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183 /* ObjectLiteralExpression */) { return rangeIsOnOneLine(sourceFile, child); } - break; + return true; case 217 /* DoStatement */: case 218 /* WhileStatement */: case 220 /* ForInStatement */: @@ -98787,6 +98865,12 @@ var ts; return childKind !== 257 /* JsxClosingElement */; case 258 /* JsxFragment */: return childKind !== 260 /* JsxClosingFragment */; + case 169 /* IntersectionType */: + case 168 /* UnionType */: + if (childKind === 165 /* TypeLiteral */) { + return false; + } + // falls through } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -98816,7 +98900,7 @@ var ts; */ function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; @@ -99386,7 +99470,7 @@ var ts; var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); } return changes; }; @@ -99427,8 +99511,12 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter) { - var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; @@ -100181,13 +100269,13 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); } } }); @@ -100195,7 +100283,7 @@ var ts; return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -100205,7 +100293,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, preferences)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -100216,14 +100304,14 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -100258,10 +100346,10 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { switch (statement.kind) { case 213 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); return false; case 215 /* ExpressionStatement */: { var expression = statement.expression; @@ -100269,7 +100357,7 @@ var ts; case 186 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], preferences)); } return false; } @@ -100284,7 +100372,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -100297,11 +100385,11 @@ var ts; } else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); } } // Move it out to its own variable statement. (This will not be used if `!foundImport`) @@ -100313,20 +100401,20 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { switch (name.kind) { case 179 /* ObjectBindingPattern */: case 180 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), + makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; default: ts.Debug.assertNever(name); } @@ -100468,7 +100556,7 @@ var ts; * Returns nodes that will replace the variable declaration for the commonjs import. * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { switch (name.kind) { case 179 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { @@ -100477,7 +100565,7 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, preferences)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -100488,12 +100576,12 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, preferences), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); default: ts.Debug.assertNever(name); } @@ -100502,7 +100590,7 @@ var ts; * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { var nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) var namedBindingsNames = ts.createMap(); @@ -100537,7 +100625,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -100577,10 +100665,10 @@ var ts; return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier) { + function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, preferences) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -103082,7 +103170,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, context.preferences))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -103568,14 +103656,14 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start); if (info) - doChange(changes, diag.file, info); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { @@ -103591,8 +103679,8 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, preferences)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -105328,7 +105416,7 @@ var ts; var refactorName = "Move to a new file"; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { - if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; @@ -105336,27 +105424,31 @@ var ts; getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === refactorName); var statements = ts.Debug.assertDefined(getStatementsToMove(context)); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - function getFirstAndLastStatementToMove(context) { + function getRangeToMove(context) { var file = context.file; var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); var statements = file.statements; var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); if (startNodeIndex === -1) return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return [statements[startNodeIndex]]; + } // Can't only partially include the start node or be partially into the next node - if (range.pos > statements[startNodeIndex].getStart(file)) + if (range.pos > startStatement.getStart(file)) return undefined; var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); // Can't be partially into the next node if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); } - function doChange(oldFile, program, toMove, changes, host) { + function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); @@ -105364,22 +105456,22 @@ var ts; var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. - changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); } // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. function getStatementsToMove(context) { - var statements = context.file.statements; - var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; var all = []; var ranges = []; - var rangeToMove = statements.slice(first, afterLast); ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { for (var i = start; i < afterEnd; i++) all.push(rangeToMove[i]); ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); }); - return { all: all, ranges: ranges }; + return all.length === 0 ? undefined : { all: all, ranges: ranges }; } function isPureImport(node) { switch (node.kind) { @@ -105407,21 +105499,21 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { deleteMovedStatements(oldFile, toMove.ranges, changes); return toMove.all; } var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, preferences); if (importsFromNewFile) { changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); } function deleteMovedStatements(sourceFile, moved, changes) { for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { @@ -105491,7 +105583,7 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { @@ -105502,13 +105594,13 @@ var ts; imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { path = ts.ensurePathIsNonModuleName(path); if (useEs6Imports) { var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); - return ts.makeImportIfNecessary(defaultImport, specifiers, path); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, preferences); } else { ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. @@ -105607,7 +105699,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -105639,7 +105731,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -109022,7 +109114,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = /** @class */ (function (_super) { @@ -111989,7 +112082,7 @@ var ts; if (this.host.realpath) { this.realpathToScriptInfos = ts.createMultiMap(); } - this.currentDirectory = this.host.getCurrentDirectory(); + this.currentDirectory = server.toNormalizedPath(this.host.getCurrentDirectory()); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation && ts.ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)); @@ -112008,7 +112101,7 @@ var ts; hostInfo: "Unknown host", extraFileExtensions: [] }; - this.documentRegistry = ts.createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.currentDirectory); + this.documentRegistry = ts.createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this); var watchLogLevel = this.logger.hasLevel(server.LogLevel.verbose) ? ts.WatchLogLevel.Verbose : this.logger.loggingEnabled() ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None; var log = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return _this.logger.info(s); }) : ts.noop; @@ -112025,6 +112118,17 @@ var ts; ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); }; + /*@internal*/ + ProjectService.prototype.setDocument = function (key, path, sourceFile) { + var info = this.getScriptInfoForPath(path); + ts.Debug.assert(!!info); + info.cacheSourceFile = { key: key, sourceFile: sourceFile }; + }; + /*@internal*/ + ProjectService.prototype.getDocument = function (key, path) { + var info = this.getScriptInfoForPath(path); + return info && info.cacheSourceFile && info.cacheSourceFile.key === key && info.cacheSourceFile.sourceFile; + }; /* @internal */ ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { this.ensureProjectStructuresUptoDate(); @@ -114328,6 +114432,7 @@ var ts; this.logger = opts.logger; this.canUseEvents = opts.canUseEvents; this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate; var throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = this.canUseEvents ? opts.eventHandler || (function (event) { return _this.defaultEventHandler(event); }) @@ -114399,7 +114504,7 @@ var ts; var _this = this; this.projectService.logger.info("got projects updated in background, updating diagnostics for " + openFiles); if (openFiles.length) { - if (!this.suppressDiagnosticEvents) { + if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { var checkList_1 = this.createCheckList(openFiles); // For now only queue error checking for open files. We can change this to include non open files as well this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, /*requireOpen*/ true); }); diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index b449fc853c6..2ac57dfce79 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1734,9 +1734,10 @@ declare namespace ts { emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. @@ -2359,6 +2360,11 @@ declare namespace ts { code: number; source?: string; } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; + } enum DiagnosticCategory { Warning = 0, Error = 1, @@ -2754,7 +2760,7 @@ declare namespace ts { /** Gets the transformed source files. */ transformed: T[]; /** Gets diagnostics for the transformation. */ - diagnostics?: Diagnostic[]; + diagnostics?: DiagnosticWithLocation[]; /** * Gets a substitute for a node, if one is available; otherwise, returns the original node. * @@ -2960,7 +2966,7 @@ declare namespace ts { } declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): Diagnostic[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -4497,9 +4503,10 @@ declare namespace ts { } interface LanguageService { cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(fileName: string): Diagnostic[]; - getSuggestionDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. diff --git a/lib/typescript.js b/lib/typescript.js index 5e0417f5f17..7b58425beb5 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -2539,23 +2539,6 @@ var ts; return to; } ts.addRange = addRange; - /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - */ - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; /** * @return Whether the value was added. */ @@ -3446,6 +3429,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -6274,7 +6265,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -6630,7 +6621,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -8898,6 +8889,27 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Appends a range of value to begin of an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; /** * Determine if the given comment is a triple-slash * @@ -15606,6 +15618,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -22879,7 +22892,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -23509,6 +23522,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -24257,22 +24280,22 @@ var ts; (node.kind === 237 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304 /* Ambient */) && - (node.kind !== 213 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -28901,7 +28924,7 @@ var ts; // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -28929,6 +28952,11 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } @@ -28936,7 +28964,7 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; @@ -29010,7 +29038,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // Any meaning of a module symbol is always accessible via an `import` type return { accessibility: 0 /* Accessible */ @@ -29061,6 +29089,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -29356,9 +29387,10 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928 /* 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); @@ -29860,7 +29892,7 @@ var ts; // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; @@ -35006,7 +35038,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -38282,10 +38316,12 @@ var ts; // all inferences were made to top-level occurrences of the type parameter, and // the type parameter has no constraint or its constraint includes no primitive or literal types, and // the type parameter was fixed during inference or does not occur at top-level in the return type. - var widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + 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. @@ -40592,6 +40628,25 @@ var ts; return getContextualType(attribute.parent); } } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 71 /* Identifier */: + return true; + case 184 /* PropertyAccessExpression */: + case 190 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { @@ -40608,8 +40663,8 @@ var ts; continue; if (prop.kind !== 269 /* PropertyAssignment */) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -45357,14 +45412,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768 /* TypeParameter */) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216 /* UnionOrIntersection */) { @@ -45376,11 +45423,9 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */ | 64 /* NumberLiteral */ | 1024 /* UniqueESSymbol */) || - constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 2 /* String */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + maybeTypeOfKind(constraint, 4 /* Number */) && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 512 /* ESSymbol */) && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a @@ -50817,7 +50862,7 @@ var ts; } // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -54663,6 +54708,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -57550,7 +57597,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -58984,7 +59031,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -60071,7 +60118,8 @@ var ts; * @param node The type reference node. */ function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -60097,8 +60145,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } /** @@ -60607,7 +60656,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -60848,7 +60897,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -61657,7 +61706,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -62256,7 +62305,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -62284,7 +62333,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -63377,7 +63426,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -63631,7 +63680,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -63744,7 +63793,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -64387,7 +64436,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { @@ -64968,7 +65017,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -66643,7 +66692,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -68879,7 +68928,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -69102,7 +69151,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -70371,7 +70420,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -78224,8 +78273,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -79031,11 +79079,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } /** @@ -85690,16 +85746,16 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier) { + function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) - : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier, preferences.quotePreference === "single") : moduleSpecifier); } ts.makeImport = makeImport; function symbolNameNoDefault(symbol) { @@ -89748,6 +89804,11 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. @@ -89770,8 +89831,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -89802,13 +89862,26 @@ var ts; var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } 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); + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } @@ -89818,6 +89891,9 @@ var ts; // return it as is. if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } // If we're acquiring, then this is the first time this LS is asking for this document. // Increase our ref count so we know there's another LS using the document. If we're @@ -89828,6 +89904,7 @@ var ts; entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -89845,6 +89922,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -89852,11 +89936,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -90359,6 +90444,9 @@ var ts; else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } // If a reference is a class expression, the exported node would be its parent. @@ -91802,6 +91890,70 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { + var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; + var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); + if (newPath !== undefined) { + var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); + changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); + } + } + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + var configFile = program.getCompilerOptions().configFile; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); + if (oldFile) { + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + } + } + function isRef(toUpdate) { + return "fileName" in toUpdate; + } + function getImportsToUpdate(program, oldFilePath, host) { + var result = []; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var ref = _c[_b]; + if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { + result.push({ sourceFile: sourceFile, toUpdate: ref }); + } + } + for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { + var importStringLiteral = _e[_d]; + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + // We may or may not have picked up on the file being renamed, so maybe successfully resolved to oldFilePath, or maybe that's in failedLookupLocations + if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { + result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); + } + } + } + return result; + } + function getPathUpdater(oldFilePath, newFilePath, host) { + // Get the relative path from old to new location, and append it on to the end of imports and normalize. + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + return function (oldPath) { + if (!ts.pathIsRelative(oldPath)) + return; + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + }; + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -93582,7 +93734,7 @@ var ts; function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -93620,8 +93772,8 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - // The JSX factory symbol is always used. - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { @@ -93801,73 +93953,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); - return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { - var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; - var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); - if (newPath !== undefined) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } - }); - } - ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); - } - } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var checker = program.getTypeChecker(); - var result = []; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (!program.getSourceFileFromReference(sourceFile, ref) && ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - // If it resolved to something already, ignore. - if (checker.getSymbolAtLocation(importStringLiteral)) - continue; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } - } - return result; - } - function getPathUpdater(oldFilePath, newFilePath, host) { - // Get the relative path from old to new location, and append it on to the end of imports and normalize. - var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; - } - function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); - } -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { @@ -95430,6 +95515,7 @@ var ts; } } } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; @@ -98702,8 +98788,9 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { case 215 /* ExpressionStatement */: case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: @@ -98725,7 +98812,6 @@ var ts; case 186 /* CallExpression */: case 187 /* NewExpression */: case 213 /* VariableStatement */: - case 231 /* VariableDeclaration */: case 248 /* ExportAssignment */: case 224 /* ReturnStatement */: case 200 /* ConditionalExpression */: @@ -98748,22 +98834,14 @@ var ts; case 246 /* NamedImports */: case 251 /* ExportSpecifier */: case 247 /* ImportSpecifier */: - case 269 /* PropertyAssignment */: case 151 /* PropertyDeclaration */: return true; - } - return false; - } - function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { - var childKind = child ? child.kind : 0 /* Unknown */; - switch (parent.kind) { case 231 /* VariableDeclaration */: case 269 /* PropertyAssignment */: - case 183 /* ObjectLiteralExpression */: if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183 /* ObjectLiteralExpression */) { return rangeIsOnOneLine(sourceFile, child); } - break; + return true; case 217 /* DoStatement */: case 218 /* WhileStatement */: case 220 /* ForInStatement */: @@ -98787,6 +98865,12 @@ var ts; return childKind !== 257 /* JsxClosingElement */; case 258 /* JsxFragment */: return childKind !== 260 /* JsxClosingFragment */; + case 169 /* IntersectionType */: + case 168 /* UnionType */: + if (childKind === 165 /* TypeLiteral */) { + return false; + } + // falls through } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -98816,7 +98900,7 @@ var ts; */ function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; @@ -99386,7 +99470,7 @@ var ts; var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); } return changes; }; @@ -99427,8 +99511,12 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter) { - var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; @@ -100181,13 +100269,13 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); } } }); @@ -100195,7 +100283,7 @@ var ts; return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -100205,7 +100293,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, preferences)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -100216,14 +100304,14 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -100258,10 +100346,10 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { switch (statement.kind) { case 213 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); return false; case 215 /* ExpressionStatement */: { var expression = statement.expression; @@ -100269,7 +100357,7 @@ var ts; case 186 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], preferences)); } return false; } @@ -100284,7 +100372,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -100297,11 +100385,11 @@ var ts; } else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); } } // Move it out to its own variable statement. (This will not be used if `!foundImport`) @@ -100313,20 +100401,20 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { switch (name.kind) { case 179 /* ObjectBindingPattern */: case 180 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), + makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; default: ts.Debug.assertNever(name); } @@ -100468,7 +100556,7 @@ var ts; * Returns nodes that will replace the variable declaration for the commonjs import. * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { switch (name.kind) { case 179 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { @@ -100477,7 +100565,7 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, preferences)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -100488,12 +100576,12 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, preferences), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); default: ts.Debug.assertNever(name); } @@ -100502,7 +100590,7 @@ var ts; * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { var nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) var namedBindingsNames = ts.createMap(); @@ -100537,7 +100625,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -100577,10 +100665,10 @@ var ts; return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier) { + function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, preferences) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -103082,7 +103170,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, context.preferences))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -103568,14 +103656,14 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start); if (info) - doChange(changes, diag.file, info); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { @@ -103591,8 +103679,8 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, preferences)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -105328,7 +105416,7 @@ var ts; var refactorName = "Move to a new file"; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { - if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; @@ -105336,27 +105424,31 @@ var ts; getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === refactorName); var statements = ts.Debug.assertDefined(getStatementsToMove(context)); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - function getFirstAndLastStatementToMove(context) { + function getRangeToMove(context) { var file = context.file; var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); var statements = file.statements; var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); if (startNodeIndex === -1) return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return [statements[startNodeIndex]]; + } // Can't only partially include the start node or be partially into the next node - if (range.pos > statements[startNodeIndex].getStart(file)) + if (range.pos > startStatement.getStart(file)) return undefined; var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); // Can't be partially into the next node if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); } - function doChange(oldFile, program, toMove, changes, host) { + function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); @@ -105364,22 +105456,22 @@ var ts; var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. - changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); } // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. function getStatementsToMove(context) { - var statements = context.file.statements; - var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; var all = []; var ranges = []; - var rangeToMove = statements.slice(first, afterLast); ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { for (var i = start; i < afterEnd; i++) all.push(rangeToMove[i]); ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); }); - return { all: all, ranges: ranges }; + return all.length === 0 ? undefined : { all: all, ranges: ranges }; } function isPureImport(node) { switch (node.kind) { @@ -105407,21 +105499,21 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { deleteMovedStatements(oldFile, toMove.ranges, changes); return toMove.all; } var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, preferences); if (importsFromNewFile) { changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); } function deleteMovedStatements(sourceFile, moved, changes) { for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { @@ -105491,7 +105583,7 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { @@ -105502,13 +105594,13 @@ var ts; imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { path = ts.ensurePathIsNonModuleName(path); if (useEs6Imports) { var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); - return ts.makeImportIfNecessary(defaultImport, specifiers, path); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, preferences); } else { ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. @@ -105607,7 +105699,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -105639,7 +105731,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -109022,7 +109114,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = /** @class */ (function (_super) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index d237cc98eee..35200473ef5 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -1734,9 +1734,10 @@ declare namespace ts { emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. @@ -2359,6 +2360,11 @@ declare namespace ts { code: number; source?: string; } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; + } enum DiagnosticCategory { Warning = 0, Error = 1, @@ -2754,7 +2760,7 @@ declare namespace ts { /** Gets the transformed source files. */ transformed: T[]; /** Gets diagnostics for the transformation. */ - diagnostics?: Diagnostic[]; + diagnostics?: DiagnosticWithLocation[]; /** * Gets a substitute for a node, if one is available; otherwise, returns the original node. * @@ -2960,7 +2966,7 @@ declare namespace ts { } declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): Diagnostic[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -4497,9 +4503,10 @@ declare namespace ts { } interface LanguageService { cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(fileName: string): Diagnostic[]; - getSuggestionDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 5e0417f5f17..7b58425beb5 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -2539,23 +2539,6 @@ var ts; return to; } ts.addRange = addRange; - /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - */ - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; /** * @return Whether the value was added. */ @@ -3446,6 +3429,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -6274,7 +6265,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -6630,7 +6621,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -8898,6 +8889,27 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Appends a range of value to begin of an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; /** * Determine if the given comment is a triple-slash * @@ -15606,6 +15618,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -22879,7 +22892,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -23509,6 +23522,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -24257,22 +24280,22 @@ var ts; (node.kind === 237 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304 /* Ambient */) && - (node.kind !== 213 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -28901,7 +28924,7 @@ var ts; // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -28929,6 +28952,11 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } @@ -28936,7 +28964,7 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; @@ -29010,7 +29038,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // Any meaning of a module symbol is always accessible via an `import` type return { accessibility: 0 /* Accessible */ @@ -29061,6 +29089,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -29356,9 +29387,10 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928 /* 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); @@ -29860,7 +29892,7 @@ var ts; // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; @@ -35006,7 +35038,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -38282,10 +38316,12 @@ var ts; // all inferences were made to top-level occurrences of the type parameter, and // the type parameter has no constraint or its constraint includes no primitive or literal types, and // the type parameter was fixed during inference or does not occur at top-level in the return type. - var widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + 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. @@ -40592,6 +40628,25 @@ var ts; return getContextualType(attribute.parent); } } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 71 /* Identifier */: + return true; + case 184 /* PropertyAccessExpression */: + case 190 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { @@ -40608,8 +40663,8 @@ var ts; continue; if (prop.kind !== 269 /* PropertyAssignment */) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -45357,14 +45412,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768 /* TypeParameter */) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216 /* UnionOrIntersection */) { @@ -45376,11 +45423,9 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */ | 64 /* NumberLiteral */ | 1024 /* UniqueESSymbol */) || - constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 2 /* String */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + maybeTypeOfKind(constraint, 4 /* Number */) && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 512 /* ESSymbol */) && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a @@ -50817,7 +50862,7 @@ var ts; } // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -54663,6 +54708,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -57550,7 +57597,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -58984,7 +59031,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -60071,7 +60118,8 @@ var ts; * @param node The type reference node. */ function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -60097,8 +60145,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } /** @@ -60607,7 +60656,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -60848,7 +60897,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -61657,7 +61706,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -62256,7 +62305,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -62284,7 +62333,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -63377,7 +63426,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -63631,7 +63680,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -63744,7 +63793,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -64387,7 +64436,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { @@ -64968,7 +65017,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -66643,7 +66692,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -68879,7 +68928,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -69102,7 +69151,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -70371,7 +70420,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -78224,8 +78273,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -79031,11 +79079,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } /** @@ -85690,16 +85746,16 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier) { + function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) - : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier, preferences.quotePreference === "single") : moduleSpecifier); } ts.makeImport = makeImport; function symbolNameNoDefault(symbol) { @@ -89748,6 +89804,11 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. @@ -89770,8 +89831,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -89802,13 +89862,26 @@ var ts; var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } 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); + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } @@ -89818,6 +89891,9 @@ var ts; // return it as is. if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } // If we're acquiring, then this is the first time this LS is asking for this document. // Increase our ref count so we know there's another LS using the document. If we're @@ -89828,6 +89904,7 @@ var ts; entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -89845,6 +89922,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -89852,11 +89936,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -90359,6 +90444,9 @@ var ts; else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } // If a reference is a class expression, the exported node would be its parent. @@ -91802,6 +91890,70 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { + var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; + var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); + if (newPath !== undefined) { + var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); + changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); + } + } + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + var configFile = program.getCompilerOptions().configFile; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); + if (oldFile) { + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + } + } + function isRef(toUpdate) { + return "fileName" in toUpdate; + } + function getImportsToUpdate(program, oldFilePath, host) { + var result = []; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var ref = _c[_b]; + if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { + result.push({ sourceFile: sourceFile, toUpdate: ref }); + } + } + for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { + var importStringLiteral = _e[_d]; + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + // We may or may not have picked up on the file being renamed, so maybe successfully resolved to oldFilePath, or maybe that's in failedLookupLocations + if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { + result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); + } + } + } + return result; + } + function getPathUpdater(oldFilePath, newFilePath, host) { + // Get the relative path from old to new location, and append it on to the end of imports and normalize. + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + return function (oldPath) { + if (!ts.pathIsRelative(oldPath)) + return; + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + }; + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -93582,7 +93734,7 @@ var ts; function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -93620,8 +93772,8 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - // The JSX factory symbol is always used. - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { @@ -93801,73 +93953,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); - return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { - var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; - var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); - if (newPath !== undefined) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } - }); - } - ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); - } - } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var checker = program.getTypeChecker(); - var result = []; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (!program.getSourceFileFromReference(sourceFile, ref) && ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - // If it resolved to something already, ignore. - if (checker.getSymbolAtLocation(importStringLiteral)) - continue; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } - } - return result; - } - function getPathUpdater(oldFilePath, newFilePath, host) { - // Get the relative path from old to new location, and append it on to the end of imports and normalize. - var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; - } - function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); - } -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { @@ -95430,6 +95515,7 @@ var ts; } } } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; @@ -98702,8 +98788,9 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { case 215 /* ExpressionStatement */: case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: @@ -98725,7 +98812,6 @@ var ts; case 186 /* CallExpression */: case 187 /* NewExpression */: case 213 /* VariableStatement */: - case 231 /* VariableDeclaration */: case 248 /* ExportAssignment */: case 224 /* ReturnStatement */: case 200 /* ConditionalExpression */: @@ -98748,22 +98834,14 @@ var ts; case 246 /* NamedImports */: case 251 /* ExportSpecifier */: case 247 /* ImportSpecifier */: - case 269 /* PropertyAssignment */: case 151 /* PropertyDeclaration */: return true; - } - return false; - } - function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { - var childKind = child ? child.kind : 0 /* Unknown */; - switch (parent.kind) { case 231 /* VariableDeclaration */: case 269 /* PropertyAssignment */: - case 183 /* ObjectLiteralExpression */: if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183 /* ObjectLiteralExpression */) { return rangeIsOnOneLine(sourceFile, child); } - break; + return true; case 217 /* DoStatement */: case 218 /* WhileStatement */: case 220 /* ForInStatement */: @@ -98787,6 +98865,12 @@ var ts; return childKind !== 257 /* JsxClosingElement */; case 258 /* JsxFragment */: return childKind !== 260 /* JsxClosingFragment */; + case 169 /* IntersectionType */: + case 168 /* UnionType */: + if (childKind === 165 /* TypeLiteral */) { + return false; + } + // falls through } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -98816,7 +98900,7 @@ var ts; */ function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; @@ -99386,7 +99470,7 @@ var ts; var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); } return changes; }; @@ -99427,8 +99511,12 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter) { - var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; @@ -100181,13 +100269,13 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); } } }); @@ -100195,7 +100283,7 @@ var ts; return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -100205,7 +100293,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, preferences)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -100216,14 +100304,14 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -100258,10 +100346,10 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { switch (statement.kind) { case 213 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); return false; case 215 /* ExpressionStatement */: { var expression = statement.expression; @@ -100269,7 +100357,7 @@ var ts; case 186 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], preferences)); } return false; } @@ -100284,7 +100372,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -100297,11 +100385,11 @@ var ts; } else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); } } // Move it out to its own variable statement. (This will not be used if `!foundImport`) @@ -100313,20 +100401,20 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { switch (name.kind) { case 179 /* ObjectBindingPattern */: case 180 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), + makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; default: ts.Debug.assertNever(name); } @@ -100468,7 +100556,7 @@ var ts; * Returns nodes that will replace the variable declaration for the commonjs import. * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { switch (name.kind) { case 179 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { @@ -100477,7 +100565,7 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, preferences)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -100488,12 +100576,12 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, preferences), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); default: ts.Debug.assertNever(name); } @@ -100502,7 +100590,7 @@ var ts; * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { var nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) var namedBindingsNames = ts.createMap(); @@ -100537,7 +100625,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -100577,10 +100665,10 @@ var ts; return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier) { + function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, preferences) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -103082,7 +103170,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, context.preferences))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -103568,14 +103656,14 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start); if (info) - doChange(changes, diag.file, info); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { @@ -103591,8 +103679,8 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, preferences)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -105328,7 +105416,7 @@ var ts; var refactorName = "Move to a new file"; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { - if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; @@ -105336,27 +105424,31 @@ var ts; getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === refactorName); var statements = ts.Debug.assertDefined(getStatementsToMove(context)); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - function getFirstAndLastStatementToMove(context) { + function getRangeToMove(context) { var file = context.file; var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); var statements = file.statements; var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); if (startNodeIndex === -1) return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return [statements[startNodeIndex]]; + } // Can't only partially include the start node or be partially into the next node - if (range.pos > statements[startNodeIndex].getStart(file)) + if (range.pos > startStatement.getStart(file)) return undefined; var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); // Can't be partially into the next node if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); } - function doChange(oldFile, program, toMove, changes, host) { + function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); @@ -105364,22 +105456,22 @@ var ts; var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. - changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); } // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. function getStatementsToMove(context) { - var statements = context.file.statements; - var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; var all = []; var ranges = []; - var rangeToMove = statements.slice(first, afterLast); ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { for (var i = start; i < afterEnd; i++) all.push(rangeToMove[i]); ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); }); - return { all: all, ranges: ranges }; + return all.length === 0 ? undefined : { all: all, ranges: ranges }; } function isPureImport(node) { switch (node.kind) { @@ -105407,21 +105499,21 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { deleteMovedStatements(oldFile, toMove.ranges, changes); return toMove.all; } var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, preferences); if (importsFromNewFile) { changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); } function deleteMovedStatements(sourceFile, moved, changes) { for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { @@ -105491,7 +105583,7 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { @@ -105502,13 +105594,13 @@ var ts; imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { path = ts.ensurePathIsNonModuleName(path); if (useEs6Imports) { var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); - return ts.makeImportIfNecessary(defaultImport, specifiers, path); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, preferences); } else { ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. @@ -105607,7 +105699,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -105639,7 +105731,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -109022,7 +109114,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = /** @class */ (function (_super) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 23bca5d1167..24d6ed7e506 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -980,15 +980,6 @@ var ts; return to; } ts.addRange = addRange; - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; function pushIfUnique(array, toAdd, equalityComparer) { if (contains(array, toAdd, equalityComparer)) { return false; @@ -1735,6 +1726,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -4204,7 +4203,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -4560,7 +4559,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -4915,6 +4914,19 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { if (text.charCodeAt(commentPos + 1) === 47 && commentPos + 2 < commentEnd && @@ -12434,6 +12446,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind);