diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 033c72ccc65..7cfcb413307 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -573,6 +573,12 @@ + + + + + + @@ -1527,6 +1533,12 @@ + + + + + + @@ -2967,6 +2979,12 @@ + + + + + + diff --git a/lib/lib.es2015.collection.d.ts b/lib/lib.es2015.collection.d.ts index 33417297531..84b9ad6c0ef 100644 --- a/lib/lib.es2015.collection.d.ts +++ b/lib/lib.es2015.collection.d.ts @@ -78,7 +78,7 @@ interface ReadonlySet { readonly size: number; } -interface WeakSet { +interface WeakSet { add(value: T): this; delete(value: T): boolean; has(value: T): boolean; diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index 07cb929648a..72f20e690ea 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -200,7 +200,7 @@ interface SetConstructor { new (iterable: Iterable): Set; } -interface WeakSet { } +interface WeakSet { } interface WeakSetConstructor { new (iterable: Iterable): WeakSet; diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index 0b97de7157d..65ce71cf3e3 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -138,7 +138,7 @@ interface Set { readonly [Symbol.toStringTag]: "Set"; } -interface WeakSet { +interface WeakSet { readonly [Symbol.toStringTag]: "WeakSet"; } diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 3751aaebc69..e408ce819b1 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -4704,7 +4704,7 @@ interface ReadonlySet { readonly size: number; } -interface WeakSet { +interface WeakSet { add(value: T): this; delete(value: T): boolean; has(value: T): boolean; @@ -4954,7 +4954,7 @@ interface SetConstructor { new (iterable: Iterable): Set; } -interface WeakSet { } +interface WeakSet { } interface WeakSetConstructor { new (iterable: Iterable): WeakSet; @@ -5649,7 +5649,7 @@ interface Set { readonly [Symbol.toStringTag]: "Set"; } -interface WeakSet { +interface WeakSet { readonly [Symbol.toStringTag]: "WeakSet"; } diff --git a/lib/tsc.js b/lib/tsc.js index 8394604267c..8523e02817e 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -486,11 +486,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -600,12 +601,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -3990,6 +4002,7 @@ var ts; Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -4065,6 +4078,7 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -4081,6 +4095,7 @@ var ts; Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); var ts; @@ -5773,6 +5788,7 @@ var ts; ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -11203,15 +11219,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -15259,7 +15267,7 @@ var ts; case 39: if (state === 0) { state = 1; - indent += scanner.getTokenText().length; + indent += 1; break; } default: @@ -15349,10 +15357,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280, start_2); @@ -15456,10 +15461,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -17671,23 +17673,9 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { setCommonJsModuleIndicator(node); return; } @@ -17741,7 +17729,7 @@ var ts; if (node.kind === 195) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { bindExportsPropertyAssignment(node); } else { @@ -17750,11 +17738,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -17922,6 +17906,28 @@ var ts; return true; } } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { @@ -19817,8 +19823,8 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, @@ -20290,10 +20296,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; var result; var lastLocation; @@ -20463,7 +20470,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -28559,6 +28568,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -29057,7 +29069,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -31581,20 +31593,25 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + var instantiatedSignatures = []; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); + } + else { + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -31733,7 +31750,7 @@ var ts; } return anyType; } - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType || emptyObjectType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); @@ -32192,7 +32209,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); @@ -35309,6 +35326,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -37201,10 +37221,10 @@ var ts; var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (declaredProp) { var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); - if (prop && baseProp_1) { - var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; - if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, undefined, rootChain)) { + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, undefined, rootChain)) { issuedMemberError = true; } } @@ -57071,26 +57091,14 @@ var ts; emitExpression(node.literal); } function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432); - write("}"); - } + write("{"); + emitList(node, node.elements, 262576); + write("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304); - write("]"); - } + write("["); + emitList(node, node.elements, 262448); + write("]"); } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); diff --git a/lib/tsserver.js b/lib/tsserver.js index 84d76fb43d8..3c4ca85f057 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1551,11 +1551,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -1665,12 +1666,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -5074,6 +5086,7 @@ var ts; Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5149,6 +5162,7 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -5165,6 +5179,7 @@ var ts; Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); var ts; @@ -6006,6 +6021,7 @@ var ts; ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -13156,15 +13172,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -17256,7 +17264,7 @@ var ts; case 39: if (state === 0) { state = 1; - indent += scanner.getTokenText().length; + indent += 1; break; } default: @@ -17346,10 +17354,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280, start_2); @@ -17453,10 +17458,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -19695,23 +19697,9 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { setCommonJsModuleIndicator(node); return; } @@ -19765,7 +19753,7 @@ var ts; if (node.kind === 195) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { bindExportsPropertyAssignment(node); } else { @@ -19774,11 +19762,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -19946,6 +19930,28 @@ var ts; return true; } } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { @@ -21007,8 +21013,8 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, @@ -21577,10 +21583,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; var result; var lastLocation; @@ -21750,7 +21757,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -29846,6 +29855,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -30344,7 +30356,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -32868,20 +32880,25 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + var instantiatedSignatures = []; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); + } + else { + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -33020,7 +33037,7 @@ var ts; } return anyType; } - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType || emptyObjectType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); @@ -33479,7 +33496,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); @@ -36603,6 +36620,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -38502,10 +38522,10 @@ var ts; var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (declaredProp) { var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); - if (prop && baseProp_1) { - var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; - if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, undefined, rootChain)) { + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, undefined, rootChain)) { issuedMemberError = true; } } @@ -58547,26 +58567,14 @@ var ts; emitExpression(node.literal); } function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432); - write("}"); - } + write("{"); + emitList(node, node.elements, 262576); + write("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304); - write("]"); - } + write("["); + emitList(node, node.elements, 262448); + write("]"); } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); @@ -60075,8 +60083,8 @@ var ts; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; @@ -65327,6 +65335,10 @@ var ts; return visited; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; function suppressLeadingAndTrailingTrivia(node) { ts.Debug.assert(node !== undefined); suppressLeading(node); @@ -66636,7 +66648,7 @@ var ts; continue; } var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.get(foundFileName)) { + if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } @@ -66722,7 +66734,8 @@ var ts; var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; var includeGlob = normalizedSuffix ? "**/*" : "./*"; var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); - return ts.mapDefined(matches, function (match) { + var directories = tryGetDirectories(host, baseDirectory); + return ts.mapDefined(ts.concatenate(matches, directories), function (match) { var normalizedMatch = ts.normalizePath(match); if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { return; @@ -74470,8 +74483,12 @@ var ts; for (var token = 0; token <= 143; token++) { allTokens.push(token); } - function anyTokenExcept(token) { - return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3])); @@ -74653,11 +74670,11 @@ var ts; rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2, 1), rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2, 1), rule("NoSpaceBeforeComma", anyToken, 26, [isNonJsxSameLineTokenContext], 8), - rule("SpaceBetweenStatements", [20, 81, 82, 73], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2), - rule("SpaceAfterTryFinally", [102, 87], 17, [isNonJsxSameLineTokenContext], 2), - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120), 21, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120, 73), 21, [isNonJsxSameLineTokenContext], 8), rule("NoSpaceAfterCloseBracket", 22, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8), rule("SpaceAfterSemicolon", 25, anyToken, [isNonJsxSameLineTokenContext], 2), + rule("SpaceBetweenStatements", [20, 81, 82, 73], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2), + rule("SpaceAfterTryFinally", [102, 87], 17, [isNonJsxSameLineTokenContext], 2), ]; return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); } @@ -76587,6 +76604,10 @@ var ts; var startPosition = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.replaceWithSingle(sourceFile, pos, pos, ts.createToken(modifier), { suffix: " " }); + }; ChangeTracker.prototype.changeIdentifierToPropertyAccess = function (sourceFile, prefix, node) { var startPosition = getAdjustedStartPosition(sourceFile, node, {}, Position.Start); this.replaceWithSingle(sourceFile, startPosition, startPosition, ts.createPropertyAccess(ts.createIdentifier(prefix), ""), {}); @@ -78005,6 +78026,78 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, + }); + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, false); + var containingFunction = ts.getContainingFunction(token); + var insertBefore; + switch (containingFunction.kind) { + case 152: + insertBefore = containingFunction.name; + break; + case 229: + case 187: + insertBefore = ts.findChildOfKind(containingFunction, 89, sourceFile); + break; + case 188: + insertBefore = ts.findChildOfKind(containingFunction, 19, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } + return { + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) + }; + } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 71 || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 120, insertBefore); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -78532,7 +78625,7 @@ var ts; symbolName = context.symbolName; } else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455, false)); symbolName = symbol.name; } else { @@ -78656,6 +78749,7 @@ var ts; } return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -79924,6 +80018,438 @@ var ts; })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var actionName = "Convert to ES6 module"; + var convertToEs6Module = { + name: actionName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module), + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(convertToEs6Module); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { + return undefined; + } + var node = ts.getTokenAtPosition(file, startPosition, false); + return !isAtTriggerLocation(file, node) ? undefined : [ + { + name: convertToEs6Module.name, + description: convertToEs6Module.description, + actions: [ + { + description: convertToEs6Module.description, + name: actionName, + }, + ], + }, + ]; + } + function isAtTriggerLocation(sourceFile, node, onSecondTry) { + if (onSecondTry === void 0) { onSecondTry = false; } + switch (node.kind) { + case 182: + return isAtTopLevelRequire(node); + case 180: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); + case 228: + var decl = node.declarations[0]; + return ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); + case 227: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node.initializer); + default: + return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, true); + } + } + function isAtTopLevelRequire(call) { + if (!ts.isRequireCall(call, true)) { + return false; + } + var propAccess = call.parent; + var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; + if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { + return true; + } + if (!ts.isVariableDeclaration(varDecl)) { + return false; + } + var varDeclList = varDecl.parent; + if (varDeclList.kind !== 228) { + return false; + } + var varStatement = varDeclList.parent; + return varStatement.kind === 209 && varStatement.parent.kind === 269; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var file = context.file, program = context.program; + ts.Debug.assert(ts.isSourceFileJavaScript(file)); + var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, file, changes); + } + } + }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var parent = moduleSpecifier.parent; + switch (parent.kind) { + case 249: { + var importEq = parent.parent; + changes.replaceNode(importingFile, importEq, makeImport(importEq.name, undefined, moduleSpecifier.text)); + break; + } + case 182: { + var call = parent; + if (ts.isRequireCall(call, false)) { + changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + } + break; + } + } + } + } + function convertFileToEs6Module(sourceFile, checker, changes, target) { + 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); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 107455, true))) { + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 209: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 211: { + var expression = statement.expression; + switch (expression.kind) { + case 182: { + if (ts.isRequireCall(expression, true)) { + changes.replaceNode(sourceFile, statement, makeImport(undefined, undefined, expression.arguments[0].text)); + } + return false; + } + case 195: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); + } + else { + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 175: + case 176: { + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier), + makeConst(undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 71: + return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 154: + case 155: + case 266: + case 267: + return undefined; + case 265: { + var _a = prop, name = _a.name, initializer = _a.initializer; + return !ts.isIdentifier(name) ? undefined : convertExportsDotXEquals(name.text, initializer); + } + case 152: { + var m = prop; + return !ts.isIdentifier(m.name) ? undefined : functionExpressionToDeclaration(m.name.text, [ts.createToken(84)], m); + } + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + var newNodes = [ + makeConst(undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84), ts.createToken(79)]; + switch (exported.kind) { + case 187: + case 188: { + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 200: { + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 182: + if (ts.isRequireCall(exported, true)) { + return convertReExportAll(exported.arguments[0], checker); + } + default: + return [[ts.createExportAssignment(undefined, undefined, false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84)]; + switch (exported.kind) { + case 187: + case 188: + return functionExpressionToDeclaration(name, modifiers, exported); + case 200: + return classExpressionToDeclaration(name, modifiers, exported); + default: + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + switch (name.kind) { + case 175: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(undefined, importSpecifiers, moduleSpecifier)]; + } + } + case 176: { + var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier), + makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + var nameSymbol = checker.getSymbolAtLocation(name); + var namedBindingsNames = ts.createMap(); + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 180: + return parent.name !== node; + case 177: + return parent.propertyName !== node; + default: + return true; + } + } + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + 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) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier) + : makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifier)); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, undefined, init)], 2)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration(undefined, undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var refactor; (function (refactor) { @@ -81119,7 +81645,7 @@ var ts; } for (var i = 0; i < scopes.length; i++) { var scope = scopes[i]; - var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, false); if (resolvedSymbol === symbol) { continue; } @@ -83717,17 +84243,6 @@ var ts; Msg["Info"] = "Info"; Msg["Perf"] = "Perf"; })(Msg = server.Msg || (server.Msg = {})); - function getProjectRootPath(project) { - switch (project.projectKind) { - case server.ProjectKind.Configured: - return ts.getDirectoryPath(project.getProjectName()); - case server.ProjectKind.Inferred: - return ""; - case server.ProjectKind.External: - var projectName = ts.normalizeSlashes(project.getProjectName()); - return ts.getDirectoryPath(projectName); - } - } function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), @@ -83735,7 +84250,7 @@ var ts; compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, - projectRootPath: getProjectRootPath(project), + projectRootPath: project.getCurrentDirectory(), cachePath: cachePath, kind: "discover" }; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index b0dc9e3b6eb..3eabea4435a 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -901,6 +901,7 @@ declare namespace ts { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; + name: never; } interface LiteralLikeNode extends Node { text: string; @@ -1362,6 +1363,7 @@ declare namespace ts { interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; parent?: SourceFile | ModuleBlock; + /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier?: Expression; @@ -3288,7 +3290,7 @@ declare namespace ts { declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ - function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral; + function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 23dd2e0451f..5abb05e26e4 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1775,11 +1775,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -1900,12 +1901,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -5728,6 +5740,7 @@ var ts; Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5803,6 +5816,7 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -5819,6 +5833,7 @@ var ts; Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); /// @@ -5828,6 +5843,7 @@ var ts; ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -7159,11 +7175,6 @@ var ts; (node.typeArguments[0].kind === 136 /* StringKeyword */ || node.typeArguments[0].kind === 133 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - /** - * Returns true if the node is a CallExpression to the identifier 'require' with - * exactly one argument (of the form 'require("name")'). - * This function does not test if the node is in a JavaScript file or not. - */ function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 182 /* CallExpression */) { return false; @@ -13971,15 +13982,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -19014,7 +19017,7 @@ var ts; if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; - indent += scanner.getTokenText().length; + indent += 1; break; } // record the * as a comment @@ -19108,10 +19111,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_2); @@ -19217,10 +19217,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -25004,27 +25001,13 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' // is still pointing to 'module.exports'. // We do not want to consider this as 'export=' since a module can have only one of these. // Similarly we do not want to treat 'module.exports = exports' as an 'export='. var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { // Mark it as a module in case there are no other exports in the file setCommonJsModuleIndicator(node); return; @@ -25095,7 +25078,7 @@ var ts; if (node.kind === 195 /* BinaryExpression */) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { // This can be an alias for the 'exports' or 'module.exports' names, e.g. // var util = module.exports; // util.property = function ... @@ -25107,11 +25090,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -25321,6 +25300,29 @@ var ts; return true; } } + /* @internal */ + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } /** * Computes the transform flags for a node, given the transform flags of its subtree * @@ -26558,8 +26560,8 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, @@ -27193,10 +27195,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -27431,7 +27434,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -36680,6 +36685,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173 /* MappedType */: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -37255,7 +37263,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -40276,20 +40285,27 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + // Instantiate in context of source type + var instantiatedSignatures = []; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + } + else { + // Do not instantiate if no source type is provided - type parameters and their constraints will be used by contextual typing + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -40497,7 +40513,7 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType || emptyObjectType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -41083,7 +41099,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -44904,6 +44920,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -47273,11 +47292,11 @@ var ts; var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (declaredProp) { var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); - if (prop && baseProp_1) { + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { var rootChain = function () { return ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; - if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, /*message*/ undefined, rootChain)) { + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { issuedMemberError = true; } } @@ -73517,26 +73536,14 @@ var ts; // Binding patterns // function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); - write("}"); - } + write("{"); + emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + write("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304 /* ArrayBindingPatternElements */); - write("]"); - } + write("["); + emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + write("]"); } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); @@ -75230,8 +75237,8 @@ var ts; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; @@ -79220,6 +79227,10 @@ var ts; return visited; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ @@ -80812,7 +80823,7 @@ var ts; continue; } var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.get(foundFileName)) { + if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } @@ -80915,8 +80926,9 @@ var ts; // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + var directories = tryGetDirectories(host, baseDirectory); // Trim away prefix and suffix - return ts.mapDefined(matches, function (match) { + return ts.mapDefined(ts.concatenate(matches, directories), function (match) { var normalizedMatch = ts.normalizePath(match); if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { return; @@ -90051,8 +90063,12 @@ var ts; for (var token = 0 /* FirstToken */; token <= 143 /* LastToken */; token++) { allTokens.push(token); } - function anyTokenExcept(token) { - return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); @@ -90290,15 +90306,15 @@ var ts; rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), - rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); } @@ -92561,6 +92577,10 @@ var ts; var startPosition = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.replaceWithSingle(sourceFile, pos, pos, ts.createToken(modifier), { suffix: " " }); + }; ChangeTracker.prototype.changeIdentifierToPropertyAccess = function (sourceFile, prefix, node) { var startPosition = getAdjustedStartPosition(sourceFile, node, {}, Position.Start); this.replaceWithSingle(sourceFile, startPosition, startPosition, ts.createPropertyAccess(ts.createIdentifier(prefix), ""), {}); @@ -94117,6 +94137,79 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, + }); + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var containingFunction = ts.getContainingFunction(token); + var insertBefore; + switch (containingFunction.kind) { + case 152 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + break; + case 188 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } + return { + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) + }; + } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -94740,7 +94833,7 @@ var ts; } else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */, /*excludeGlobals*/ false)); symbolName = symbol.name; } else { @@ -94877,6 +94970,7 @@ var ts; // Need `|| "_"` to ensure result isn't empty. return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -95805,6 +95899,7 @@ var ts; /// /// /// +/// /// /// /// @@ -96283,6 +96378,493 @@ var ts; })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var actionName = "Convert to ES6 module"; + var convertToEs6Module = { + name: actionName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module), + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(convertToEs6Module); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { + return undefined; + } + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + return !isAtTriggerLocation(file, node) ? undefined : [ + { + name: convertToEs6Module.name, + description: convertToEs6Module.description, + actions: [ + { + description: convertToEs6Module.description, + name: actionName, + }, + ], + }, + ]; + } + function isAtTriggerLocation(sourceFile, node, onSecondTry) { + if (onSecondTry === void 0) { onSecondTry = false; } + switch (node.kind) { + case 182 /* CallExpression */: + return isAtTopLevelRequire(node); + case 180 /* PropertyAccessExpression */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); + case 228 /* VariableDeclarationList */: + var decl = node.declarations[0]; + return ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); + case 227 /* VariableDeclaration */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node.initializer); + default: + return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true); + } + } + function isAtTopLevelRequire(call) { + if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + var propAccess = call.parent; + var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; + if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { + return true; + } + if (!ts.isVariableDeclaration(varDecl)) { + return false; + } + var varDeclList = varDecl.parent; + if (varDeclList.kind !== 228 /* VariableDeclarationList */) { + return false; + } + var varStatement = varDeclList.parent; + return varStatement.kind === 209 /* VariableStatement */ && varStatement.parent.kind === 269 /* SourceFile */; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var file = context.file, program = context.program; + ts.Debug.assert(ts.isSourceFileJavaScript(file)); + var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, file, changes); + } + } + }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var parent = moduleSpecifier.parent; + switch (parent.kind) { + case 249 /* ExternalModuleReference */: { + var importEq = parent.parent; + changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); + break; + } + case 182 /* CallExpression */: { + var call = parent; + if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { + changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + } + break; + } + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target) { + 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); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 209 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 211 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 182 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); + } + return false; + } + case 195 /* BinaryExpression */: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); + } + else { + // Move it out to its own variable statement. + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: + case 176 /* 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), + 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)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 266 /* ShorthandPropertyAssignment */: + case 267 /* SpreadAssignment */: + return undefined; + case 265 /* PropertyAssignment */: { + var _a = prop, name = _a.name, initializer = _a.initializer; + return !ts.isIdentifier(name) ? undefined : convertExportsDotXEquals(name.text, initializer); + } + case 152 /* MethodDeclaration */: { + var m = prop; + return !ts.isIdentifier(m.name) ? undefined : functionExpressionToDeclaration(m.name.text, [ts.createToken(84 /* ExportKeyword */)], m); + } + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: { + // `module.exports = function f() {}` --> `export default function f() {}` + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 200 /* ClassExpression */: { + // `module.exports = class C {}` --> `export default class C {}` + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 182 /* CallExpression */: + if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { + return convertReExportAll(exported.arguments[0], checker); + } + // falls through + default: + // `module.exports = 0;` --> `export default 0;` + return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 200 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + /** + * Converts `const <> = require("x");`. + * 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) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 176 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + /** + * 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) { + 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(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + return parent.name !== node; + case 177 /* BindingElement */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + 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) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier)); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /// /// /* @internal */ @@ -97700,7 +98282,7 @@ var ts; } for (var i = 0; i < scopes.length; i++) { var scope = scopes[i]; - var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); if (resolvedSymbol === symbol) { continue; } @@ -97998,6 +98580,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -99954,18 +100537,6 @@ var ts; Msg["Info"] = "Info"; Msg["Perf"] = "Perf"; })(Msg = server.Msg || (server.Msg = {})); - function getProjectRootPath(project) { - switch (project.projectKind) { - case server.ProjectKind.Configured: - return ts.getDirectoryPath(project.getProjectName()); - case server.ProjectKind.Inferred: - // TODO: fixme - return ""; - case server.ProjectKind.External: - var projectName = ts.normalizeSlashes(project.getProjectName()); - return ts.getDirectoryPath(projectName); - } - } function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), @@ -99973,7 +100544,7 @@ var ts; compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, - projectRootPath: getProjectRootPath(project), + projectRootPath: project.getCurrentDirectory(), cachePath: cachePath, kind: "discover" }; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index f839deabcfb..630b7a08a28 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -901,6 +901,7 @@ declare namespace ts { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; + name: never; } interface LiteralLikeNode extends Node { text: string; @@ -1362,6 +1363,7 @@ declare namespace ts { interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; parent?: SourceFile | ModuleBlock; + /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier?: Expression; @@ -3235,7 +3237,7 @@ declare namespace ts { declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ - function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral; + function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; diff --git a/lib/typescript.js b/lib/typescript.js index 91962b22cfe..c858823e640 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1775,11 +1775,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -1900,12 +1901,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -5728,6 +5740,7 @@ var ts; Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5803,6 +5816,7 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -5819,6 +5833,7 @@ var ts; Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); /// @@ -7701,6 +7716,7 @@ var ts; ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -9032,11 +9048,6 @@ var ts; (node.typeArguments[0].kind === 136 /* StringKeyword */ || node.typeArguments[0].kind === 133 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - /** - * Returns true if the node is a CallExpression to the identifier 'require' with - * exactly one argument (of the form 'require("name")'). - * This function does not test if the node is in a JavaScript file or not. - */ function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 182 /* CallExpression */) { return false; @@ -13971,15 +13982,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -19014,7 +19017,7 @@ var ts; if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; - indent += scanner.getTokenText().length; + indent += 1; break; } // record the * as a comment @@ -19108,10 +19111,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_2); @@ -19217,10 +19217,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -21960,27 +21957,13 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' // is still pointing to 'module.exports'. // We do not want to consider this as 'export=' since a module can have only one of these. // Similarly we do not want to treat 'module.exports = exports' as an 'export='. var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { // Mark it as a module in case there are no other exports in the file setCommonJsModuleIndicator(node); return; @@ -22051,7 +22034,7 @@ var ts; if (node.kind === 195 /* BinaryExpression */) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { // This can be an alias for the 'exports' or 'module.exports' names, e.g. // var util = module.exports; // util.property = function ... @@ -22063,11 +22046,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -22277,6 +22256,29 @@ var ts; return true; } } + /* @internal */ + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } /** * Computes the transform flags for a node, given the transform flags of its subtree * @@ -24518,8 +24520,8 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, @@ -25153,10 +25155,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -25391,7 +25394,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -34640,6 +34645,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173 /* MappedType */: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -35215,7 +35223,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -38236,20 +38245,27 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + // Instantiate in context of source type + var instantiatedSignatures = []; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + } + else { + // Do not instantiate if no source type is provided - type parameters and their constraints will be used by contextual typing + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -38457,7 +38473,7 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType || emptyObjectType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -39043,7 +39059,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -42864,6 +42880,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -45233,11 +45252,11 @@ var ts; var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (declaredProp) { var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); - if (prop && baseProp_1) { + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { var rootChain = function () { return ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; - if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, /*message*/ undefined, rootChain)) { + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { issuedMemberError = true; } } @@ -71477,26 +71496,14 @@ var ts; // Binding patterns // function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); - write("}"); - } + write("{"); + emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + write("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304 /* ArrayBindingPatternElements */); - write("]"); - } + write("["); + emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + write("]"); } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); @@ -73190,8 +73197,8 @@ var ts; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; @@ -79220,6 +79227,10 @@ var ts; return visited; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ @@ -80207,7 +80218,7 @@ var ts; continue; } var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.get(foundFileName)) { + if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } @@ -80310,8 +80321,9 @@ var ts; // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + var directories = tryGetDirectories(host, baseDirectory); // Trim away prefix and suffix - return ts.mapDefined(matches, function (match) { + return ts.mapDefined(ts.concatenate(matches, directories), function (match) { var normalizedMatch = ts.normalizePath(match); if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { return; @@ -89446,8 +89458,12 @@ var ts; for (var token = 0 /* FirstToken */; token <= 143 /* LastToken */; token++) { allTokens.push(token); } - function anyTokenExcept(token) { - return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); @@ -89685,15 +89701,15 @@ var ts; rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), - rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); } @@ -91956,6 +91972,10 @@ var ts; var startPosition = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.replaceWithSingle(sourceFile, pos, pos, ts.createToken(modifier), { suffix: " " }); + }; ChangeTracker.prototype.changeIdentifierToPropertyAccess = function (sourceFile, prefix, node) { var startPosition = getAdjustedStartPosition(sourceFile, node, {}, Position.Start); this.replaceWithSingle(sourceFile, startPosition, startPosition, ts.createPropertyAccess(ts.createIdentifier(prefix), ""), {}); @@ -93512,6 +93532,79 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, + }); + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var containingFunction = ts.getContainingFunction(token); + var insertBefore; + switch (containingFunction.kind) { + case 152 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + break; + case 188 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } + return { + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) + }; + } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -94135,7 +94228,7 @@ var ts; } else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */, /*excludeGlobals*/ false)); symbolName = symbol.name; } else { @@ -94272,6 +94365,7 @@ var ts; // Need `|| "_"` to ensure result isn't empty. return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -95200,6 +95294,7 @@ var ts; /// /// /// +/// /// /// /// @@ -95678,6 +95773,493 @@ var ts; })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var actionName = "Convert to ES6 module"; + var convertToEs6Module = { + name: actionName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module), + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(convertToEs6Module); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { + return undefined; + } + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + return !isAtTriggerLocation(file, node) ? undefined : [ + { + name: convertToEs6Module.name, + description: convertToEs6Module.description, + actions: [ + { + description: convertToEs6Module.description, + name: actionName, + }, + ], + }, + ]; + } + function isAtTriggerLocation(sourceFile, node, onSecondTry) { + if (onSecondTry === void 0) { onSecondTry = false; } + switch (node.kind) { + case 182 /* CallExpression */: + return isAtTopLevelRequire(node); + case 180 /* PropertyAccessExpression */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); + case 228 /* VariableDeclarationList */: + var decl = node.declarations[0]; + return ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); + case 227 /* VariableDeclaration */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node.initializer); + default: + return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true); + } + } + function isAtTopLevelRequire(call) { + if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + var propAccess = call.parent; + var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; + if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { + return true; + } + if (!ts.isVariableDeclaration(varDecl)) { + return false; + } + var varDeclList = varDecl.parent; + if (varDeclList.kind !== 228 /* VariableDeclarationList */) { + return false; + } + var varStatement = varDeclList.parent; + return varStatement.kind === 209 /* VariableStatement */ && varStatement.parent.kind === 269 /* SourceFile */; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var file = context.file, program = context.program; + ts.Debug.assert(ts.isSourceFileJavaScript(file)); + var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, file, changes); + } + } + }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var parent = moduleSpecifier.parent; + switch (parent.kind) { + case 249 /* ExternalModuleReference */: { + var importEq = parent.parent; + changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); + break; + } + case 182 /* CallExpression */: { + var call = parent; + if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { + changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + } + break; + } + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target) { + 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); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 209 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 211 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 182 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); + } + return false; + } + case 195 /* BinaryExpression */: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); + } + else { + // Move it out to its own variable statement. + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: + case 176 /* 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), + 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)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 266 /* ShorthandPropertyAssignment */: + case 267 /* SpreadAssignment */: + return undefined; + case 265 /* PropertyAssignment */: { + var _a = prop, name = _a.name, initializer = _a.initializer; + return !ts.isIdentifier(name) ? undefined : convertExportsDotXEquals(name.text, initializer); + } + case 152 /* MethodDeclaration */: { + var m = prop; + return !ts.isIdentifier(m.name) ? undefined : functionExpressionToDeclaration(m.name.text, [ts.createToken(84 /* ExportKeyword */)], m); + } + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: { + // `module.exports = function f() {}` --> `export default function f() {}` + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 200 /* ClassExpression */: { + // `module.exports = class C {}` --> `export default class C {}` + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 182 /* CallExpression */: + if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { + return convertReExportAll(exported.arguments[0], checker); + } + // falls through + default: + // `module.exports = 0;` --> `export default 0;` + return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 200 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + /** + * Converts `const <> = require("x");`. + * 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) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 176 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + /** + * 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) { + 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(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + return parent.name !== node; + case 177 /* BindingElement */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + 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) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier)); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /// /// /* @internal */ @@ -97095,7 +97677,7 @@ var ts; } for (var i = 0; i < scopes.length; i++) { var scope = scopes[i]; - var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); if (resolvedSymbol === symbol) { continue; } @@ -97393,6 +97975,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 34b115e106f..935c4311c0b 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -901,6 +901,7 @@ declare namespace ts { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; + name: never; } interface LiteralLikeNode extends Node { text: string; @@ -1362,6 +1363,7 @@ declare namespace ts { interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; parent?: SourceFile | ModuleBlock; + /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier?: Expression; @@ -3235,7 +3237,7 @@ declare namespace ts { declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ - function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral; + function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 91962b22cfe..c858823e640 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -1775,11 +1775,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -1900,12 +1901,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -5728,6 +5740,7 @@ var ts; Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5803,6 +5816,7 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -5819,6 +5833,7 @@ var ts; Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); /// @@ -7701,6 +7716,7 @@ var ts; ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -9032,11 +9048,6 @@ var ts; (node.typeArguments[0].kind === 136 /* StringKeyword */ || node.typeArguments[0].kind === 133 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - /** - * Returns true if the node is a CallExpression to the identifier 'require' with - * exactly one argument (of the form 'require("name")'). - * This function does not test if the node is in a JavaScript file or not. - */ function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 182 /* CallExpression */) { return false; @@ -13971,15 +13982,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -19014,7 +19017,7 @@ var ts; if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; - indent += scanner.getTokenText().length; + indent += 1; break; } // record the * as a comment @@ -19108,10 +19111,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_2); @@ -19217,10 +19217,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -21960,27 +21957,13 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' // is still pointing to 'module.exports'. // We do not want to consider this as 'export=' since a module can have only one of these. // Similarly we do not want to treat 'module.exports = exports' as an 'export='. var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { // Mark it as a module in case there are no other exports in the file setCommonJsModuleIndicator(node); return; @@ -22051,7 +22034,7 @@ var ts; if (node.kind === 195 /* BinaryExpression */) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { // This can be an alias for the 'exports' or 'module.exports' names, e.g. // var util = module.exports; // util.property = function ... @@ -22063,11 +22046,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -22277,6 +22256,29 @@ var ts; return true; } } + /* @internal */ + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } /** * Computes the transform flags for a node, given the transform flags of its subtree * @@ -24518,8 +24520,8 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, @@ -25153,10 +25155,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -25391,7 +25394,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -34640,6 +34645,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173 /* MappedType */: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -35215,7 +35223,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -38236,20 +38245,27 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + // Instantiate in context of source type + var instantiatedSignatures = []; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + } + else { + // Do not instantiate if no source type is provided - type parameters and their constraints will be used by contextual typing + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -38457,7 +38473,7 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType || emptyObjectType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -39043,7 +39059,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -42864,6 +42880,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -45233,11 +45252,11 @@ var ts; var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (declaredProp) { var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); - var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); - if (prop && baseProp_1) { + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { var rootChain = function () { return ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; - if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, /*message*/ undefined, rootChain)) { + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { issuedMemberError = true; } } @@ -71477,26 +71496,14 @@ var ts; // Binding patterns // function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); - write("}"); - } + write("{"); + emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + write("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304 /* ArrayBindingPatternElements */); - write("]"); - } + write("["); + emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + write("]"); } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); @@ -73190,8 +73197,8 @@ var ts; ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; @@ -79220,6 +79227,10 @@ var ts; return visited; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ @@ -80207,7 +80218,7 @@ var ts; continue; } var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.get(foundFileName)) { + if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } @@ -80310,8 +80321,9 @@ var ts; // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + var directories = tryGetDirectories(host, baseDirectory); // Trim away prefix and suffix - return ts.mapDefined(matches, function (match) { + return ts.mapDefined(ts.concatenate(matches, directories), function (match) { var normalizedMatch = ts.normalizePath(match); if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { return; @@ -89446,8 +89458,12 @@ var ts; for (var token = 0 /* FirstToken */; token <= 143 /* LastToken */; token++) { allTokens.push(token); } - function anyTokenExcept(token) { - return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); @@ -89685,15 +89701,15 @@ var ts; rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), - // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), - rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); } @@ -91956,6 +91972,10 @@ var ts; var startPosition = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.replaceWithSingle(sourceFile, pos, pos, ts.createToken(modifier), { suffix: " " }); + }; ChangeTracker.prototype.changeIdentifierToPropertyAccess = function (sourceFile, prefix, node) { var startPosition = getAdjustedStartPosition(sourceFile, node, {}, Position.Start); this.replaceWithSingle(sourceFile, startPosition, startPosition, ts.createPropertyAccess(ts.createIdentifier(prefix), ""), {}); @@ -93512,6 +93532,79 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, + }); + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var containingFunction = ts.getContainingFunction(token); + var insertBefore; + switch (containingFunction.kind) { + case 152 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + break; + case 188 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } + return { + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) + }; + } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -94135,7 +94228,7 @@ var ts; } else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */, /*excludeGlobals*/ false)); symbolName = symbol.name; } else { @@ -94272,6 +94365,7 @@ var ts; // Need `|| "_"` to ensure result isn't empty. return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -95200,6 +95294,7 @@ var ts; /// /// /// +/// /// /// /// @@ -95678,6 +95773,493 @@ var ts; })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var actionName = "Convert to ES6 module"; + var convertToEs6Module = { + name: actionName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module), + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(convertToEs6Module); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { + return undefined; + } + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + return !isAtTriggerLocation(file, node) ? undefined : [ + { + name: convertToEs6Module.name, + description: convertToEs6Module.description, + actions: [ + { + description: convertToEs6Module.description, + name: actionName, + }, + ], + }, + ]; + } + function isAtTriggerLocation(sourceFile, node, onSecondTry) { + if (onSecondTry === void 0) { onSecondTry = false; } + switch (node.kind) { + case 182 /* CallExpression */: + return isAtTopLevelRequire(node); + case 180 /* PropertyAccessExpression */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); + case 228 /* VariableDeclarationList */: + var decl = node.declarations[0]; + return ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); + case 227 /* VariableDeclaration */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node.initializer); + default: + return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true); + } + } + function isAtTopLevelRequire(call) { + if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + var propAccess = call.parent; + var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; + if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { + return true; + } + if (!ts.isVariableDeclaration(varDecl)) { + return false; + } + var varDeclList = varDecl.parent; + if (varDeclList.kind !== 228 /* VariableDeclarationList */) { + return false; + } + var varStatement = varDeclList.parent; + return varStatement.kind === 209 /* VariableStatement */ && varStatement.parent.kind === 269 /* SourceFile */; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var file = context.file, program = context.program; + ts.Debug.assert(ts.isSourceFileJavaScript(file)); + var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, file, changes); + } + } + }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var parent = moduleSpecifier.parent; + switch (parent.kind) { + case 249 /* ExternalModuleReference */: { + var importEq = parent.parent; + changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); + break; + } + case 182 /* CallExpression */: { + var call = parent; + if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { + changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + } + break; + } + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target) { + 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); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 209 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 211 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 182 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); + } + return false; + } + case 195 /* BinaryExpression */: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); + } + else { + // Move it out to its own variable statement. + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: + case 176 /* 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), + 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)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 266 /* ShorthandPropertyAssignment */: + case 267 /* SpreadAssignment */: + return undefined; + case 265 /* PropertyAssignment */: { + var _a = prop, name = _a.name, initializer = _a.initializer; + return !ts.isIdentifier(name) ? undefined : convertExportsDotXEquals(name.text, initializer); + } + case 152 /* MethodDeclaration */: { + var m = prop; + return !ts.isIdentifier(m.name) ? undefined : functionExpressionToDeclaration(m.name.text, [ts.createToken(84 /* ExportKeyword */)], m); + } + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: { + // `module.exports = function f() {}` --> `export default function f() {}` + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 200 /* ClassExpression */: { + // `module.exports = class C {}` --> `export default class C {}` + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 182 /* CallExpression */: + if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { + return convertReExportAll(exported.arguments[0], checker); + } + // falls through + default: + // `module.exports = 0;` --> `export default 0;` + return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 200 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + /** + * Converts `const <> = require("x");`. + * 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) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 176 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + /** + * 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) { + 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(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + return parent.name !== node; + case 177 /* BindingElement */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + 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) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier)); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /// /// /* @internal */ @@ -97095,7 +97677,7 @@ var ts; } for (var i = 0; i < scopes.length; i++) { var scope = scopes[i]; - var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); if (resolvedSymbol === symbol) { continue; } @@ -97393,6 +97975,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index ead7d59877d..6196e0ef01f 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -496,11 +496,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -610,12 +611,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -4000,6 +4012,7 @@ var ts; Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -4075,6 +4088,7 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), @@ -4091,6 +4105,7 @@ var ts; Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); var ts; @@ -4098,6 +4113,7 @@ var ts; ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -11213,15 +11229,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -15269,7 +15277,7 @@ var ts; case 39: if (state === 0) { state = 1; - indent += scanner.getTokenText().length; + indent += 1; break; } default: @@ -15359,10 +15367,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280, start_2); @@ -15466,10 +15471,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) {