diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg
index e4080a9bb37..61eb41991c4 100644
--- a/lib/enu/diagnosticMessages.generated.json.lcg
+++ b/lib/enu/diagnosticMessages.generated.json.lcg
@@ -51,6 +51,12 @@
+ -
+
+
+
+
+
-
@@ -63,12 +69,6 @@
- -
-
-
-
-
-
-
@@ -693,6 +693,18 @@
+ -
+
+
+
+
+
+ -
+
+
+
+
+
-
@@ -705,12 +717,24 @@
+ -
+
+
+
+
+
-
+ -
+
+
+
+
+
-
@@ -1077,9 +1101,9 @@
- -
+
-
-
+
@@ -1209,9 +1233,9 @@
- -
+
-
-
+
@@ -1317,9 +1341,15 @@
- -
+
-
-
+
+
+
+
+ -
+
+
@@ -4299,6 +4329,12 @@
+ -
+
+
+
+
+
-
@@ -5541,6 +5577,12 @@
+ -
+
+
+
+
+
-
diff --git a/lib/tsc.js b/lib/tsc.js
index f04ae41349c..ca3538f4e20 100644
--- a/lib/tsc.js
+++ b/lib/tsc.js
@@ -14,7 +14,8 @@ and limitations under the License.
***************************************************************************** */
-"use strict";"use strict";
+"use strict";
+"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
@@ -60,7 +61,7 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook
var ts;
(function (ts) {
ts.versionMajorMinor = "3.2";
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".1";
})(ts || (ts = {}));
(function (ts) {
ts.emptyArray = [];
@@ -3269,7 +3270,7 @@ var ts;
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
- An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."),
+ An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
@@ -3376,7 +3377,7 @@ var ts;
Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
- A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."),
+ A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."),
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
@@ -3459,7 +3460,7 @@ var ts;
_0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
- Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."),
+ Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
@@ -3490,7 +3491,7 @@ var ts;
Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
- Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."),
+ Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
@@ -3535,6 +3536,7 @@ var ts;
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
+ Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
@@ -3634,6 +3636,7 @@ var ts;
Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
+ The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
@@ -4029,6 +4032,7 @@ var ts;
Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
+ Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
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."),
@@ -4124,6 +4128,7 @@ var ts;
Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
+ Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
@@ -4192,6 +4197,9 @@ var ts;
Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"),
Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
+ Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
+ Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
+ Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
};
})(ts || (ts = {}));
var ts;
@@ -4370,11 +4378,23 @@ var ts;
return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text);
}
ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
- function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) {
+ function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) {
+ return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, true);
+ }
+ ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits;
+ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
if (line < 0 || line >= lineStarts.length) {
- ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ if (allowEdits) {
+ line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
+ }
+ else {
+ ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ }
}
var res = lineStarts[line] + character;
+ if (allowEdits) {
+ return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
+ }
if (line < lineStarts.length - 1) {
ts.Debug.assert(res < lineStarts[line + 1]);
}
@@ -9711,6 +9731,31 @@ var ts;
return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
}
ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
+ function isTypeNodeKind(kind) {
+ return (kind >= 163 && kind <= 183)
+ || kind === 120
+ || kind === 143
+ || kind === 135
+ || kind === 146
+ || kind === 136
+ || kind === 123
+ || kind === 138
+ || kind === 139
+ || kind === 100
+ || kind === 106
+ || kind === 141
+ || kind === 96
+ || kind === 132
+ || kind === 211
+ || kind === 284
+ || kind === 285
+ || kind === 286
+ || kind === 287
+ || kind === 288
+ || kind === 289
+ || kind === 290;
+ }
+ ts.isTypeNodeKind = isTypeNodeKind;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -10952,6 +10997,10 @@ var ts;
|| kind === 17;
}
ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
+ function isImportOrExportSpecifier(node) {
+ return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
+ }
+ ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
function isStringTextContainingNode(node) {
return node.kind === 10 || isTemplateLiteralKind(node.kind);
}
@@ -11106,32 +11155,8 @@ var ts;
|| kind === 159;
}
ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
- function isTypeNodeKind(kind) {
- return (kind >= 163 && kind <= 183)
- || kind === 120
- || kind === 143
- || kind === 135
- || kind === 146
- || kind === 136
- || kind === 123
- || kind === 138
- || kind === 139
- || kind === 100
- || kind === 106
- || kind === 141
- || kind === 96
- || kind === 132
- || kind === 211
- || kind === 284
- || kind === 285
- || kind === 286
- || kind === 287
- || kind === 288
- || kind === 289
- || kind === 290;
- }
function isTypeNode(node) {
- return isTypeNodeKind(node.kind);
+ return ts.isTypeNodeKind(node.kind);
}
ts.isTypeNode = isTypeNode;
function isFunctionOrConstructorTypeNode(node) {
@@ -13335,53 +13360,46 @@ var ts;
return visitNodes(cbNode, cbNodes, node.tags);
case 299:
case 305:
- if (node.isNameFirst) {
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.typeExpression);
- }
- else {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.name);
- }
- case 300:
- return visitNode(cbNode, node.typeExpression);
- case 302:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ (node.isNameFirst
+ ? visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.typeExpression)
+ : visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.name));
case 295:
- return visitNode(cbNode, node.class);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.class);
case 303:
- return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.constraint) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters);
case 304:
- if (node.typeExpression &&
- node.typeExpression.kind === 283) {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.fullName);
- }
- else {
- return visitNode(cbNode, node.fullName) ||
- visitNode(cbNode, node.typeExpression);
- }
+ return visitNode(cbNode, node.tagName) ||
+ (node.typeExpression &&
+ node.typeExpression.kind === 283
+ ? visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.fullName)
+ : visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression));
case 297:
- return visitNode(cbNode, node.fullName) ||
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
+ case 300:
+ case 302:
case 301:
- return visitNode(cbNode, node.typeExpression);
case 298:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.typeExpression);
case 293:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- ts.forEach(node.typeParameters, cbNode) ||
+ return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
case 292:
- if (node.jsDocPropertyTags) {
- for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
- var tag = _a[_i];
- visitNode(cbNode, tag);
- }
- }
- return;
+ return ts.forEach(node.jsDocPropertyTags, cbNode);
+ case 294:
+ case 296:
+ return visitNode(cbNode, node.tagName);
case 308:
return visitNode(cbNode, node.expression);
}
@@ -18751,6 +18769,18 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "diagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_diagnostic_information
+ },
+ {
+ name: "extendedDiagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_verbose_diagnostic_information
+ },
];
ts.optionDeclarations = ts.commonOptionsWithBuild.concat([
{
@@ -19202,18 +19232,6 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
},
- {
- name: "diagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_diagnostic_information
- },
- {
- name: "extendedDiagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_verbose_diagnostic_information
- },
{
name: "resolveJsonModule",
type: "boolean",
@@ -23028,6 +23046,7 @@ var ts;
}
}
function bindJSDocTypeAlias(node) {
+ node.tagName.parent = node;
if (node.fullName) {
setParentPointers(node, node.fullName);
}
@@ -23957,7 +23976,7 @@ var ts;
return true;
}
var node = symbol.valueDeclaration;
- if (ts.isCallExpression(node)) {
+ if (node && ts.isCallExpression(node)) {
return !!ts.getAssignedExpandoInitializer(node);
}
var init = !node ? undefined :
@@ -25307,17 +25326,7 @@ var ts;
var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
return parsed ? isImplementationOfOverload(parsed) : undefined;
},
- getImmediateAliasedSymbol: function (symbol) {
- ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here.");
- var links = getSymbolLinks(symbol);
- if (!links.immediateTarget) {
- var node = getDeclarationOfAliasSymbol(symbol);
- if (!node)
- return ts.Debug.fail();
- links.immediateTarget = getTargetOfAliasDeclaration(node, true);
- }
- return links.immediateTarget;
- },
+ getImmediateAliasedSymbol: getImmediateAliasedSymbol,
getAliasedSymbol: resolveAlias,
getEmitResolver: getEmitResolver,
getExportsOfModule: getExportsOfModuleAsArray,
@@ -25345,6 +25354,7 @@ var ts;
getNumberType: function () { return numberType; },
createPromiseType: createPromiseType,
createArrayType: createArrayType,
+ getElementTypeOfArrayType: getElementTypeOfArrayType,
getBooleanType: function () { return booleanType; },
getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
@@ -25749,7 +25759,11 @@ var ts;
(source.flags | target.flags) & 67108864) {
ts.Debug.assert(source !== target);
if (!(target.flags & 33554432)) {
- target = cloneSymbol(resolveSymbol(target));
+ var resolvedTarget = resolveSymbol(target);
+ if (resolvedTarget === unknownSymbol) {
+ return source;
+ }
+ target = cloneSymbol(resolvedTarget);
}
if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
target.constEnumOnlyModule = false;
@@ -26794,8 +26808,8 @@ var ts;
undefined;
return initializer || decl;
}
- function resolveExternalModuleName(location, moduleReferenceExpression) {
- return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
+ function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
+ return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0);
}
function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
if (isForAugmentation === void 0) { isForAugmentation = false; }
@@ -26823,7 +26837,7 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
- if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) {
+ if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
errorOnImplicitAnyModule(false, errorNode, resolvedModule, moduleReference);
}
return getMergedSymbol(sourceFile.symbol);
@@ -27074,14 +27088,58 @@ var ts;
function getParentOfSymbol(symbol) {
return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
}
+ function getAlternativeContainingModules(symbol, enclosingDeclaration) {
+ var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
+ var id = "" + getNodeId(containingFile);
+ var links = getSymbolLinks(symbol);
+ var results;
+ if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
+ return results;
+ }
+ if (containingFile && containingFile.imports) {
+ for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
+ var importRef = _a[_i];
+ if (ts.nodeIsSynthesized(importRef))
+ continue;
+ var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, true);
+ if (!resolvedModule)
+ continue;
+ var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, resolvedModule);
+ }
+ if (ts.length(results)) {
+ (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
+ return results;
+ }
+ }
+ if (links.extendedContainers) {
+ return links.extendedContainers;
+ }
+ var otherFiles = host.getSourceFiles();
+ for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
+ var file = otherFiles_1[_b];
+ if (!ts.isExternalModule(file))
+ continue;
+ var sym = getSymbolOfNode(file);
+ var ref = getAliasForSymbolInContainer(sym, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, sym);
+ }
+ return links.extendedContainers = results || ts.emptyArray;
+ }
function getContainersOfSymbol(symbol, enclosingDeclaration) {
var container = getParentOfSymbol(symbol);
if (container) {
var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
+ var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920, false)) {
- return ts.concatenate([container], additionalContainers);
+ return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers);
}
- return ts.append(additionalContainers, container);
+ var res = ts.append(additionalContainers, container);
+ return ts.concatenate(res, reexportContainers);
}
var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; });
if (!ts.length(candidates)) {
@@ -27450,7 +27508,7 @@ var ts;
}
function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
if (flags === void 0) { flags = 4; }
- var nodeFlags = 3112960;
+ var nodeFlags = 70221824;
if (flags & 2) {
nodeFlags |= 128;
}
@@ -27461,7 +27519,7 @@ var ts;
nodeFlags |= 16384;
}
if (flags & 16) {
- nodeFlags |= 67108864;
+ nodeFlags |= 134217728;
}
var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
@@ -27484,7 +27542,7 @@ var ts;
else {
sigOutput = kind === 1 ? 161 : 160;
}
- var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512);
+ var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | 512);
var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4, sig, sourceFile, ts.getTrailingSemicolonOmittingWriter(writer));
@@ -27495,7 +27553,7 @@ var ts;
if (flags === void 0) { flags = 1048576 | 16384; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var noTruncation = compilerOptions.noErrorTruncation || flags & 1;
- var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | (noTruncation ? 1 : 0), writer);
+ var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | (noTruncation ? 1 : 0), writer);
if (typeNode === undefined)
return ts.Debug.fail("should always get typenode");
var options = { removeComments: true };
@@ -27545,7 +27603,7 @@ var ts;
var context = {
enclosingDeclaration: enclosingDeclaration,
flags: flags || 0,
- tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 ? {
+ tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 ? {
getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
getSourceFiles: function () { return host.getSourceFiles(); },
getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); })
@@ -27790,11 +27848,7 @@ var ts;
return symbolToTypeNode(typeAlias, context, 67897832);
}
else {
- context.approximateLength += 3;
- if (!(context.flags & 1)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), undefined);
- }
- return ts.createKeywordTypeNode(120);
+ return createElidedInformationPlaceholder(context);
}
}
else {
@@ -27806,11 +27860,7 @@ var ts;
}
var depth = context.symbolDepth.get(id) || 0;
if (depth > 10) {
- context.approximateLength += 3;
- if (!(context.flags & 1)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), undefined);
- }
- return ts.createKeywordTypeNode(120);
+ return createElidedInformationPlaceholder(context);
}
context.symbolDepth.set(id, depth + 1);
context.visitedTypes.set(typeId, true);
@@ -27986,10 +28036,15 @@ var ts;
typeElements.push(signatureToSignatureDeclarationHelper(signature, 161, context));
}
if (resolvedType.stringIndexInfo) {
- var indexInfo = resolvedType.objectFlags & 2048 ?
- createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) :
- resolvedType.stringIndexInfo;
- typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0, context));
+ var indexSignature = void 0;
+ if (resolvedType.objectFlags & 2048) {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0, context);
+ indexSignature.type = createElidedInformationPlaceholder(context);
+ }
+ else {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context);
+ }
+ typeElements.push(indexSignature);
}
if (resolvedType.numberIndexInfo) {
typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context));
@@ -28020,8 +28075,16 @@ var ts;
return typeElements.length ? typeElements : undefined;
}
}
+ function createElidedInformationPlaceholder(context) {
+ context.approximateLength += 3;
+ if (!(context.flags & 1)) {
+ return ts.createTypeReferenceNode(ts.createIdentifier("..."), undefined);
+ }
+ return ts.createKeywordTypeNode(120);
+ }
function addPropertyToElementList(propertySymbol, context, typeElements) {
- var propertyType = ts.getCheckFlags(propertySymbol) & 2048 && context.flags & 33554432 ?
+ var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048);
+ var propertyType = propertyIsReverseMapped && context.flags & 33554432 ?
anyType : getTypeOfSymbol(propertySymbol);
var saveEnclosingDeclaration = context.enclosingDeclaration;
context.enclosingDeclaration = undefined;
@@ -28050,8 +28113,14 @@ var ts;
}
else {
var savedFlags = context.flags;
- context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048) ? 33554432 : 0;
- var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120);
+ context.flags |= propertyIsReverseMapped ? 33554432 : 0;
+ var propertyTypeNode = void 0;
+ if (propertyIsReverseMapped && !!(savedFlags & 33554432)) {
+ propertyTypeNode = createElidedInformationPlaceholder(context);
+ }
+ else {
+ propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120);
+ }
context.flags = savedFlags;
var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133)] : undefined;
if (modifiers) {
@@ -28225,7 +28294,7 @@ var ts;
context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning);
var chain;
var isTypeParameter = symbol.flags & 262144;
- if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64) && !(context.flags & 67108864)) {
+ if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64) && !(context.flags & 134217728)) {
chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, true));
ts.Debug.assert(chain && chain.length > 0);
}
@@ -28235,12 +28304,21 @@ var ts;
return chain;
function getSymbolChain(symbol, meaning, endOfChain) {
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128));
+ var parentSpecifiers;
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
- var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
- if (ts.length(parents)) {
- for (var _i = 0, _a = parents; _i < _a.length; _i++) {
- var parent = _a[_i];
+ var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
+ if (ts.length(parents_1)) {
+ parentSpecifiers = parents_1.map(function (symbol) {
+ return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
+ ? getSpecifierForModuleSymbol(symbol, context)
+ : undefined;
+ });
+ var indices = parents_1.map(function (_, i) { return i; });
+ indices.sort(sortByBestName);
+ var sortedParents = indices.map(function (i) { return parents_1[i]; });
+ for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
+ var parent = sortedParents_1[_i];
var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false);
if (parentChain) {
accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
@@ -28259,6 +28337,21 @@ var ts;
}
return [symbol];
}
+ function sortByBestName(a, b) {
+ var specifierA = parentSpecifiers[a];
+ var specifierB = parentSpecifiers[b];
+ if (specifierA && specifierB) {
+ var isBRelative = ts.pathIsRelative(specifierB);
+ if (ts.pathIsRelative(specifierA) === isBRelative) {
+ return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
+ }
+ if (isBRelative) {
+ return -1;
+ }
+ return 1;
+ }
+ return 0;
+ }
}
}
function typeParametersToTypeParameterDeclarations(symbol, context) {
@@ -28337,6 +28430,12 @@ var ts;
var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
var specifier = getSpecifierForModuleSymbol(chain[0], context);
+ if (!(context.flags & 67108864) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
+ context.encounteredError = true;
+ if (context.tracker.reportLikelyUnsafeImportRequiredError) {
+ context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
+ }
+ }
var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
@@ -28472,7 +28571,7 @@ var ts;
if (flags === void 0) { flags = 16384; }
return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
function typePredicateToStringWorker(writer) {
- var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512));
+ var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | 512));
var printer = ts.createPrinter({ removeComments: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4, predicate, sourceFile, writer);
@@ -29734,7 +29833,7 @@ var ts;
return type.resolvedBaseTypes = ts.emptyArray;
}
if (!isValidBaseType(baseType)) {
- error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType));
+ error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType));
return type.resolvedBaseTypes = ts.emptyArray;
}
if (type === baseType || hasBaseType(baseType, type)) {
@@ -29782,7 +29881,7 @@ var ts;
}
}
else {
- error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface);
+ error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -32667,7 +32766,7 @@ var ts;
if (accessExpression) {
markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 100);
if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) {
- error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop));
+ error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
return missingType;
}
if (cacheSymbol) {
@@ -34671,7 +34770,8 @@ var ts;
var bestMatchingType = findMatchingDiscriminantType(source, target) ||
findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
findBestTypeForObjectLiteral(source, target) ||
- findBestTypeForInvokable(source, target);
+ findBestTypeForInvokable(source, target) ||
+ findMostOverlappyType(source, target);
isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], true);
}
return 0;
@@ -34706,6 +34806,30 @@ var ts;
return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
}
}
+ function findMostOverlappyType(source, unionTarget) {
+ var bestMatch;
+ var matchingCount = 0;
+ for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
+ var target_1 = _a[_i];
+ var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]);
+ if (overlap.flags & 4194304) {
+ bestMatch = target_1;
+ matchingCount = Infinity;
+ }
+ else if (overlap.flags & 1048576) {
+ var len = ts.length(overlap.types);
+ if (len >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = len;
+ }
+ }
+ else if (!(overlap.flags & 131072) && 1 >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = 1;
+ }
+ }
+ return bestMatch;
+ }
function findMatchingDiscriminantType(source, target) {
if (target.flags & 1048576) {
var sourceProperties = getPropertiesOfObjectType(source);
@@ -35651,10 +35775,7 @@ var ts;
sourceHasRestParameter === targetHasRestParameter) {
return true;
}
- var sourceRestCount = sourceHasRestParameter ? 1 : 0;
- var targetRestCount = targetHasRestParameter ? 1 : 0;
- if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount ||
- sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) {
+ if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
return true;
}
return false;
@@ -35744,6 +35865,9 @@ var ts;
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4) && type.target === globalReadonlyArrayType;
}
+ function getElementTypeOfArrayType(type) {
+ return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined;
+ }
function isArrayLikeType(type) {
return ts.getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) ||
!(type.flags & 98304) && isTypeAssignableTo(type, anyReadonlyArrayType);
@@ -36075,6 +36199,16 @@ var ts;
diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
break;
case 151:
+ var param = declaration;
+ if (ts.isIdentifier(param.name) &&
+ (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
+ param.parent.parameters.indexOf(param) > -1 &&
+ (resolveName(param, param.name.escapedText, 67897832, undefined, param.name.escapedText, true) ||
+ param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
+ var newName = "arg" + param.parent.parameters.indexOf(param);
+ errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
+ return;
+ }
diagnostic = declaration.dotDotDotToken ?
noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage :
noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
@@ -38177,7 +38311,12 @@ var ts;
return errorType;
}
if (isReadonlySymbol(localOrExportSymbol)) {
- error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol));
+ if (localOrExportSymbol.flags & 3) {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
+ }
+ else {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
+ }
return errorType;
}
}
@@ -39374,6 +39513,17 @@ var ts;
var unionType = propTypes.length ? getUnionType(propTypes, 2) : undefinedType;
return createIndexInfo(unionType, false);
}
+ function getImmediateAliasedSymbol(symbol) {
+ ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here.");
+ var links = getSymbolLinks(symbol);
+ if (!links.immediateTarget) {
+ var node = getDeclarationOfAliasSymbol(symbol);
+ if (!node)
+ return ts.Debug.fail();
+ links.immediateTarget = getTargetOfAliasDeclaration(node, true);
+ }
+ return links.immediateTarget;
+ }
function checkObjectLiteral(node, checkMode) {
var inDestructuringPattern = ts.isAssignmentTarget(node);
checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
@@ -39763,13 +39913,28 @@ var ts;
function getJsxElementChildrenPropertyName(jsxNamespace) {
return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
- function getUninstantiatedJsxSignaturesOfType(elementType) {
- var signatures = getSignaturesOfType(elementType, 1);
- if (signatures.length === 0) {
- signatures = getSignaturesOfType(elementType, 0);
+ function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
+ if (elementType.flags & 4) {
+ return [anySignature];
}
- if (signatures.length === 0 && elementType.flags & 1048576) {
- signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType));
+ else if (elementType.flags & 128) {
+ var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
+ if (!intrinsicType) {
+ error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
+ return ts.emptyArray;
+ }
+ else {
+ var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
+ return [fakeSignature];
+ }
+ }
+ var apparentElemType = getApparentType(elementType);
+ var signatures = getSignaturesOfType(apparentElemType, 1);
+ if (signatures.length === 0) {
+ signatures = getSignaturesOfType(apparentElemType, 0);
+ }
+ if (signatures.length === 0 && apparentElemType.flags & 1048576) {
+ signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
}
return signatures;
}
@@ -40071,7 +40236,7 @@ var ts;
checkPropertyAccessibility(node, left.kind === 98, apparentType, prop);
if (assignmentKind) {
if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) {
- error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right));
+ error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
return errorType;
}
}
@@ -41351,20 +41516,8 @@ var ts;
if (apparentType === errorType) {
return resolveErrorCall(node);
}
- if (exprTypes.flags & 128) {
- var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node);
- if (!intrinsicType) {
- error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements);
- return resolveUntypedCall(node);
- }
- else {
- var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), undefined), intrinsicType, node.tagName, node.attributes);
- return fakeSignature;
- }
- }
- var signatures = getUninstantiatedJsxSignaturesOfType(apparentType);
- if (exprTypes.flags & 4 || isUntypedFunctionCall(exprTypes, apparentType, signatures.length, 0)) {
+ var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
+ if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, 0)) {
return resolveUntypedCall(node);
}
if (signatures.length === 0) {
@@ -42796,8 +42949,16 @@ var ts;
leftType;
case 59:
var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0;
- checkAssignmentDeclaration(declKind, right);
+ checkAssignmentDeclaration(declKind, rightType);
if (isAssignmentDeclaration(declKind)) {
+ if (!(rightType.flags & 524288) ||
+ declKind !== 2 &&
+ declKind !== 6 &&
+ !isEmptyObjectType(rightType) &&
+ !isFunctionObjectType(rightType) &&
+ !(ts.getObjectFlags(rightType) & 1)) {
+ checkAssignmentOperator(rightType);
+ }
return leftType;
}
else {
@@ -42812,10 +42973,9 @@ var ts;
default:
return ts.Debug.fail();
}
- function checkAssignmentDeclaration(kind, right) {
+ function checkAssignmentDeclaration(kind, rightType) {
if (kind === 2) {
- var rightType_1 = checkExpression(right, checkMode);
- for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
var prop = _a[_i];
var propType = getTypeOfSymbol(prop);
if (propType.symbol && propType.symbol.flags & 32) {
@@ -44526,7 +44686,7 @@ var ts;
}
}
function registerForUnusedIdentifiersCheck(node) {
- if (produceDiagnostics) {
+ if (produceDiagnostics && !(node.flags & 4194304)) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
@@ -44545,9 +44705,6 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 241:
- checkUnusedTypeParameters(node, addDiagnostic);
- break;
case 279:
case 244:
case 218:
@@ -44575,9 +44732,12 @@ var ts;
case 165:
case 166:
case 242:
- case 176:
+ case 241:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 176:
+ checkUnusedInferTypeParameter(node, addDiagnostic);
+ break;
default:
ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
}
@@ -44592,72 +44752,68 @@ var ts;
return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95;
}
function checkUnusedClassMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304)) {
- for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
- var member = _a[_i];
- switch (member.kind) {
- case 156:
- case 154:
- case 158:
- case 159:
- if (member.kind === 159 && member.symbol.flags & 32768) {
- break;
- }
- var symbol = getSymbolOfNode(member);
- if (!symbol.isReferenced && ts.hasModifier(member, 8)) {
- addDiagnostic(member, 0, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
- }
+ for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ switch (member.kind) {
+ case 156:
+ case 154:
+ case 158:
+ case 159:
+ if (member.kind === 159 && member.symbol.flags & 32768) {
break;
- case 157:
- for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
- var parameter = _c[_b];
- if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) {
- addDiagnostic(parameter, 0, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
- }
+ }
+ var symbol = getSymbolOfNode(member);
+ if (!symbol.isReferenced && ts.hasModifier(member, 8)) {
+ addDiagnostic(member, 0, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
+ }
+ break;
+ case 157:
+ for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
+ var parameter = _c[_b];
+ if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) {
+ addDiagnostic(parameter, 0, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
}
- break;
- case 162:
- case 217:
- break;
- default:
- ts.Debug.fail();
- }
+ }
+ break;
+ case 162:
+ case 217:
+ break;
+ default:
+ ts.Debug.fail();
}
}
}
- function checkUnusedTypeParameters(node, addDiagnostic) {
- if (node.flags & 4194304 || node.kind !== 176 && ts.last(getSymbolOfNode(node).declarations) !== node)
- return;
- if (node.kind === 176) {
- var typeParameter = node.typeParameter;
- if (isTypeParameterUnused(typeParameter)) {
- addDiagnostic(node, 1, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
- }
+ function checkUnusedInferTypeParameter(node, addDiagnostic) {
+ var typeParameter = node.typeParameter;
+ if (isTypeParameterUnused(typeParameter)) {
+ addDiagnostic(node, 1, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
}
- else {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
- if (!isTypeParameterUnused(typeParameter))
- continue;
- var name = ts.idText(typeParameter.name);
- var parent = typeParameter.parent;
- if (parent.kind !== 176 && parent.typeParameters.every(isTypeParameterUnused)) {
- if (seenParentsWithEveryUnused.tryAdd(parent)) {
- var range = ts.isJSDocTemplateTag(parent)
- ? ts.rangeOfNode(parent)
- : ts.rangeOfTypeParameters(parent.typeParameters);
- var only = typeParameters.length === 1;
- var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
- var arg0 = only ? name : undefined;
- addDiagnostic(typeParameter, 1, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
- }
- }
- else {
- addDiagnostic(typeParameter, 1, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
+ }
+ function checkUnusedTypeParameters(node, addDiagnostic) {
+ if (ts.last(getSymbolOfNode(node).declarations) !== node)
+ return;
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
+ var seenParentsWithEveryUnused = new ts.NodeSet();
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var typeParameter = typeParameters_2[_i];
+ if (!isTypeParameterUnused(typeParameter))
+ continue;
+ var name = ts.idText(typeParameter.name);
+ var parent = typeParameter.parent;
+ if (parent.kind !== 176 && parent.typeParameters.every(isTypeParameterUnused)) {
+ if (seenParentsWithEveryUnused.tryAdd(parent)) {
+ var range = ts.isJSDocTemplateTag(parent)
+ ? ts.rangeOfNode(parent)
+ : ts.rangeOfTypeParameters(parent.typeParameters);
+ var only = typeParameters.length === 1;
+ var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
+ var arg0 = only ? name : undefined;
+ addDiagnostic(typeParameter, 1, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
}
}
+ else {
+ addDiagnostic(typeParameter, 1, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
+ }
}
}
function isTypeParameterUnused(typeParameter) {
@@ -45006,9 +45162,9 @@ var ts;
var nameText = ts.getTextOfPropertyName(name);
if (nameText) {
var property = getPropertyOfType(parentType, nameText);
- markPropertyAsReferenced(property, undefined, false);
- if (parent.initializer && property) {
- checkPropertyAccessibility(parent, parent.initializer.kind === 98, parentType, property);
+ if (property) {
+ markPropertyAsReferenced(property, undefined, false);
+ checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98, parentType, property);
}
}
}
@@ -45861,7 +46017,7 @@ var ts;
}
}
else {
- error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface);
+ error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -47297,7 +47453,10 @@ var ts;
return undefined;
}
if (isDeclarationNameOrImportPropertyName(node)) {
- return getSymbolOfNode(parent);
+ var parentSymbol = getSymbolOfNode(parent);
+ return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
+ ? getImmediateAliasedSymbol(parentSymbol)
+ : parentSymbol;
}
else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
return getSymbolOfNode(parent.parent);
@@ -54576,7 +54735,7 @@ var ts;
};
function processMapping(mapping) {
var generatedPosition = generatedFile !== undefined
- ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
: -1;
var source;
var sourcePosition;
@@ -54585,7 +54744,7 @@ var ts;
var sourceFile = host.getSourceFileLike(sourceFilePath);
source = map.sources[mapping.sourceIndex];
sourcePosition = sourceFile !== undefined
- ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
: -1;
}
return {
@@ -64530,6 +64689,7 @@ var ts;
reportInaccessibleThisError: reportInaccessibleThisError,
reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
+ reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
moduleResolverHost: host,
trackReferencedAmbientModule: trackReferencedAmbientModule,
trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode
@@ -64613,6 +64773,11 @@ var ts;
context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
}
}
+ function reportLikelyUnsafeImportRequiredError(specifier) {
+ if (errorNameNode) {
+ context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
+ }
+ }
function transformRoot(node) {
if (node.kind === 279 && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
@@ -67287,7 +67452,7 @@ var ts;
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
- writePunctuation("...");
+ emitTokenWithComment(25, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
function emitClassExpression(node) {
@@ -67984,7 +68149,7 @@ var ts;
}
function emitSpreadAssignment(node) {
if (node.expression) {
- writePunctuation("...");
+ emitTokenWithComment(25, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
}
@@ -69732,7 +69897,7 @@ var ts;
var text;
try {
ts.performance.mark("beforeIORead");
- text = system.readFile(fileName, options.charset);
+ text = compilerHost.readFile(fileName);
ts.performance.mark("afterIORead");
ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
@@ -69758,7 +69923,12 @@ var ts;
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
- system.createDirectory(directoryPath);
+ if (compilerHost.createDirectory) {
+ compilerHost.createDirectory(directoryPath);
+ }
+ else {
+ system.createDirectory(directoryPath);
+ }
}
}
var outputFingerprints;
@@ -69809,7 +69979,7 @@ var ts;
}
var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
var realpath = system.realpath && (function (path) { return system.realpath(path); });
- return {
+ var compilerHost = {
getSourceFile: getSourceFile,
getDefaultLibLocation: getDefaultLibLocation,
getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
@@ -69825,10 +69995,110 @@ var ts;
getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return system.getDirectories(path); },
realpath: realpath,
- readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }
+ readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
+ createDirectory: function (d) { return system.createDirectory(d); }
};
+ return compilerHost;
}
ts.createCompilerHostWorker = createCompilerHostWorker;
+ function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) {
+ var originalReadFile = host.readFile;
+ var originalFileExists = host.fileExists;
+ var originalDirectoryExists = host.directoryExists;
+ var originalCreateDirectory = host.createDirectory;
+ var originalWriteFile = host.writeFile;
+ var originalGetSourceFile = host.getSourceFile;
+ var readFileCache = ts.createMap();
+ var fileExistsCache = ts.createMap();
+ var directoryExistsCache = ts.createMap();
+ var sourceFileCache = ts.createMap();
+ var readFileWithCache = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value || undefined;
+ return setReadFileCache(key, fileName);
+ };
+ var setReadFileCache = function (key, fileName) {
+ var newValue = originalReadFile.call(host, fileName);
+ readFileCache.set(key, newValue || false);
+ return newValue;
+ };
+ host.readFile = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value;
+ if (!ts.fileExtensionIs(fileName, ".json")) {
+ return originalReadFile.call(host, fileName);
+ }
+ return setReadFileCache(key, fileName);
+ };
+ if (useCacheForSourceFile) {
+ host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
+ var key = toPath(fileName);
+ var value = sourceFileCache.get(key);
+ if (value)
+ return value;
+ var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile);
+ if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json"))) {
+ sourceFileCache.set(key, sourceFile);
+ }
+ return sourceFile;
+ };
+ }
+ host.fileExists = function (fileName) {
+ var key = toPath(fileName);
+ var value = fileExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalFileExists.call(host, fileName);
+ fileExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
+ var key = toPath(fileName);
+ fileExistsCache.delete(key);
+ var value = readFileCache.get(key);
+ if (value && value !== data) {
+ readFileCache.delete(key);
+ sourceFileCache.delete(key);
+ }
+ else if (useCacheForSourceFile) {
+ var sourceFile = sourceFileCache.get(key);
+ if (sourceFile && sourceFile.text !== data) {
+ sourceFileCache.delete(key);
+ }
+ }
+ originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
+ };
+ if (originalDirectoryExists && originalCreateDirectory) {
+ host.directoryExists = function (directory) {
+ var key = toPath(directory);
+ var value = directoryExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalDirectoryExists.call(host, directory);
+ directoryExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.createDirectory = function (directory) {
+ var key = toPath(directory);
+ directoryExistsCache.delete(key);
+ originalCreateDirectory.call(host, directory);
+ };
+ }
+ return {
+ originalReadFile: originalReadFile,
+ originalFileExists: originalFileExists,
+ originalDirectoryExists: originalDirectoryExists,
+ originalCreateDirectory: originalCreateDirectory,
+ originalWriteFile: originalWriteFile,
+ originalGetSourceFile: originalGetSourceFile,
+ readFileWithCache: readFileWithCache
+ };
+ }
+ ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache;
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (ts.getEmitDeclarations(program.getCompilerOptions())) {
@@ -70162,6 +70432,7 @@ var ts;
var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
var resolvedProjectReferences;
var projectReferenceRedirects;
+ var mapFromFileToProjectReferenceRedirects;
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2) {
@@ -71319,14 +71590,19 @@ var ts;
ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine);
}
function getResolvedProjectReferenceToRedirect(fileName) {
- return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
- if (!referencedProject ||
- toPath(options.configFilePath) === referenceProjectPath ||
- !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) {
- return undefined;
- }
- return referencedProject;
- });
+ if (mapFromFileToProjectReferenceRedirects === undefined) {
+ mapFromFileToProjectReferenceRedirects = ts.createMap();
+ forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
+ if (referencedProject &&
+ toPath(options.configFilePath) !== referenceProjectPath) {
+ referencedProject.commandLine.fileNames.forEach(function (f) {
+ return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
+ });
+ }
+ });
+ }
+ var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
+ return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
}
function forEachResolvedProjectReference(cb) {
return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
@@ -73308,6 +73584,7 @@ var ts;
}
return count;
}
+ moduleSpecifiers.countPathComponents = countPathComponents;
function usesJsExtensionOnImports(_a) {
var imports = _a.imports;
return ts.firstDefined(imports, function (_a) {
@@ -74389,6 +74666,7 @@ var ts;
var missingRoots = ts.createMap();
var globalDependencyGraph;
var writeFileName = function (s) { return host.trace && host.trace(s); };
+ var readFileWithCache = function (f) { return host.readFile(f); };
var diagnostics = createFileMap(toPath);
var projectPendingBuild = createFileMap(toPath);
var projectErrorsReported = createFileMap(toPath);
@@ -74879,43 +75157,48 @@ var ts;
options: configFile.options,
configFileParsingDiagnostics: configFile.errors
};
+ if (host.beforeCreateProgram) {
+ host.beforeCreateProgram(options);
+ }
var program = ts.createProgram(programOptions);
var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
}
- if (ts.getEmitDeclarations(program.getCompilerOptions())) {
- var declDiagnostics = program.getDeclarationDiagnostics();
- if (declDiagnostics.length) {
- return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
- }
- }
var semanticDiagnostics = program.getSemanticDiagnostics();
if (semanticDiagnostics.length) {
return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic");
}
var newestDeclarationFileContentChangedTime = minimumDate;
var anyDtsChanged = false;
- var emitDiagnostics;
- var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); };
- ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, undefined, function (fileName, content, writeBom, onError) {
+ var declDiagnostics;
+ var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
+ var outputFiles = [];
+ ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); });
+ if (declDiagnostics) {
+ return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
+ }
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
var priorChangeTime;
- if (!anyDtsChanged && isDeclarationFile(fileName)) {
- if (host.fileExists(fileName) && host.readFile(fileName) === content) {
- priorChangeTime = host.getModifiedTime(fileName);
+ if (!anyDtsChanged && isDeclarationFile(name)) {
+ if (host.fileExists(name) && readFileWithCache(name) === text) {
+ priorChangeTime = host.getModifiedTime(name);
}
else {
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
anyDtsChanged = true;
}
}
- host.writeFile(fileName, content, writeBom, onError, ts.emptyArray);
+ ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark);
if (priorChangeTime !== undefined) {
newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
- unchangedOutputs.setValue(fileName, priorChangeTime);
+ unchangedOutputs.setValue(name, priorChangeTime);
}
});
- if (emitDiagnostics) {
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
}
var status = {
@@ -74924,11 +75207,17 @@ var ts;
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
}
}
@@ -74993,11 +75282,14 @@ var ts;
if (options.watch) {
reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode);
}
+ var _a = ts.changeCompilerHostToUseCache(host, toPath, true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache;
+ var savedReadFileWithCache = readFileWithCache;
+ readFileWithCache = newReadFileWithCache;
var graph = getGlobalDependencyGraph();
reportBuildQueue(graph);
var anyFailed = false;
- for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
- var next = _a[_i];
+ for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) {
+ var next = _b[_i];
var proj = parseConfigFile(next);
if (proj === undefined) {
reportParseConfigFileDiagnostic(next);
@@ -75034,6 +75326,13 @@ var ts;
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
+ host.readFile = originalReadFile;
+ host.fileExists = originalFileExists;
+ host.directoryExists = originalDirectoryExists;
+ host.createDirectory = originalCreateDirectory;
+ host.writeFile = originalWriteFile;
+ readFileWithCache = savedReadFileWithCache;
+ host.getSourceFile = originalGetSourceFile;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
function reportParseConfigFileDiagnostic(proj) {
@@ -75414,10 +75713,13 @@ var ts;
if (buildOptions.watch) {
reportWatchModeWithoutSysSupport();
}
- // TODO: change this to host if watch => watchHost otherwiue without wathc
- var builder = ts.createSolutionBuilder(buildOptions.watch ?
+ // TODO: change this to host if watch => watchHost otherwiue without watch
+ var buildHost = buildOptions.watch ?
ts.createSolutionBuilderWithWatchHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()) :
- ts.createSolutionBuilderHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createReportErrorSummary(buildOptions)), projects, buildOptions);
+ ts.createSolutionBuilderHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createReportErrorSummary(buildOptions));
+ buildHost.beforeCreateProgram = enableStatistics;
+ buildHost.afterProgramEmitAndDiagnostics = reportStatistics;
+ var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions);
if (buildOptions.clean) {
return ts.sys.exit(builder.cleanAllProjects());
}
@@ -75434,6 +75736,9 @@ var ts;
}
function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) {
var host = ts.createCompilerHost(options);
+ var currentDirectory = host.getCurrentDirectory();
+ var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
+ ts.changeCompilerHostToUseCache(host, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }, /*useCacheForSourceFile*/ false);
enableStatistics(options);
var programOptions = {
rootNames: rootNames,
diff --git a/lib/tsserver.js b/lib/tsserver.js
index 2e2de2b5623..d7ce6c98013 100644
--- a/lib/tsserver.js
+++ b/lib/tsserver.js
@@ -88,7 +88,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "3.2";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".1";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -3064,13 +3064,15 @@ var ts;
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
- NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors";
+ // Errors (cont.)
+ NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
+ /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
+ NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
// State
NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
- /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain";
})(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
// Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
var TypeFormatFlags;
@@ -5262,7 +5264,7 @@ var ts;
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
- An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."),
+ An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
@@ -5369,7 +5371,7 @@ var ts;
Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
- A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."),
+ A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."),
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
@@ -5452,7 +5454,7 @@ var ts;
_0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
- Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."),
+ Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
@@ -5483,7 +5485,7 @@ var ts;
Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
- Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."),
+ Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
@@ -5528,6 +5530,7 @@ var ts;
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
+ Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
@@ -5627,6 +5630,7 @@ var ts;
Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
+ The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
@@ -6022,6 +6026,7 @@ var ts;
Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
+ Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
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."),
@@ -6117,6 +6122,7 @@ var ts;
Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
+ Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
@@ -6185,6 +6191,9 @@ var ts;
Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"),
Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
+ Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
+ Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
+ Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
};
})(ts || (ts = {}));
var ts;
@@ -6414,11 +6423,28 @@ var ts;
}
ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
/* @internal */
- function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) {
+ function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) {
+ return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true);
+ }
+ ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits;
+ /* @internal */
+ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
if (line < 0 || line >= lineStarts.length) {
- ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ if (allowEdits) {
+ // Clamp line to nearest allowable value
+ line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
+ }
+ else {
+ ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ }
}
var res = lineStarts[line] + character;
+ if (allowEdits) {
+ // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
+ // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
+ // apply them to the computed position to improve accuracy
+ return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
+ }
if (line < lineStarts.length - 1) {
ts.Debug.assert(res < lineStarts[line + 1]);
}
@@ -8070,7 +8096,6 @@ var ts;
}
ts.createScanner = createScanner;
})(ts || (ts = {}));
-/** Non-internal stuff goes here */
var ts;
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -12355,6 +12380,31 @@ var ts;
return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
}
ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
+ function isTypeNodeKind(kind) {
+ return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
+ || kind === 120 /* AnyKeyword */
+ || kind === 143 /* UnknownKeyword */
+ || kind === 135 /* NumberKeyword */
+ || kind === 146 /* BigIntKeyword */
+ || kind === 136 /* ObjectKeyword */
+ || kind === 123 /* BooleanKeyword */
+ || kind === 138 /* StringKeyword */
+ || kind === 139 /* SymbolKeyword */
+ || kind === 100 /* ThisKeyword */
+ || kind === 106 /* VoidKeyword */
+ || kind === 141 /* UndefinedKeyword */
+ || kind === 96 /* NullKeyword */
+ || kind === 132 /* NeverKeyword */
+ || kind === 211 /* ExpressionWithTypeArguments */
+ || kind === 284 /* JSDocAllType */
+ || kind === 285 /* JSDocUnknownType */
+ || kind === 286 /* JSDocNullableType */
+ || kind === 287 /* JSDocNonNullableType */
+ || kind === 288 /* JSDocOptionalType */
+ || kind === 289 /* JSDocFunctionType */
+ || kind === 290 /* JSDocVariadicType */;
+ }
+ ts.isTypeNodeKind = isTypeNodeKind;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13823,6 +13873,10 @@ var ts;
|| kind === 17 /* TemplateTail */;
}
ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
+ function isImportOrExportSpecifier(node) {
+ return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
+ }
+ ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
function isStringTextContainingNode(node) {
return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
}
@@ -13991,37 +14045,13 @@ var ts;
}
ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
// Type
- function isTypeNodeKind(kind) {
- return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
- || kind === 120 /* AnyKeyword */
- || kind === 143 /* UnknownKeyword */
- || kind === 135 /* NumberKeyword */
- || kind === 146 /* BigIntKeyword */
- || kind === 136 /* ObjectKeyword */
- || kind === 123 /* BooleanKeyword */
- || kind === 138 /* StringKeyword */
- || kind === 139 /* SymbolKeyword */
- || kind === 100 /* ThisKeyword */
- || kind === 106 /* VoidKeyword */
- || kind === 141 /* UndefinedKeyword */
- || kind === 96 /* NullKeyword */
- || kind === 132 /* NeverKeyword */
- || kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
- }
/**
* Node test that determines whether a node is a valid type node.
* This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
* of a TypeNode.
*/
function isTypeNode(node) {
- return isTypeNodeKind(node.kind);
+ return ts.isTypeNodeKind(node.kind);
}
ts.isTypeNode = isTypeNode;
function isFunctionOrConstructorTypeNode(node) {
@@ -16542,53 +16572,46 @@ var ts;
return visitNodes(cbNode, cbNodes, node.tags);
case 299 /* JSDocParameterTag */:
case 305 /* JSDocPropertyTag */:
- if (node.isNameFirst) {
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.typeExpression);
- }
- else {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.name);
- }
- case 300 /* JSDocReturnTag */:
- return visitNode(cbNode, node.typeExpression);
- case 302 /* JSDocTypeTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ (node.isNameFirst
+ ? visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.typeExpression)
+ : visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.name));
case 295 /* JSDocAugmentsTag */:
- return visitNode(cbNode, node.class);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.class);
case 303 /* JSDocTemplateTag */:
- return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.constraint) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters);
case 304 /* JSDocTypedefTag */:
- if (node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */) {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.fullName);
- }
- else {
- return visitNode(cbNode, node.fullName) ||
- visitNode(cbNode, node.typeExpression);
- }
+ return visitNode(cbNode, node.tagName) ||
+ (node.typeExpression &&
+ node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ ? visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.fullName)
+ : visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression));
case 297 /* JSDocCallbackTag */:
- return visitNode(cbNode, node.fullName) ||
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
+ case 300 /* JSDocReturnTag */:
+ case 302 /* JSDocTypeTag */:
case 301 /* JSDocThisTag */:
- return visitNode(cbNode, node.typeExpression);
case 298 /* JSDocEnumTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.typeExpression);
case 293 /* JSDocSignature */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- ts.forEach(node.typeParameters, cbNode) ||
+ return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
case 292 /* JSDocTypeLiteral */:
- if (node.jsDocPropertyTags) {
- for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
- var tag = _a[_i];
- visitNode(cbNode, tag);
- }
- }
- return;
+ return ts.forEach(node.jsDocPropertyTags, cbNode);
+ case 294 /* JSDocTag */:
+ case 296 /* JSDocClassTag */:
+ return visitNode(cbNode, node.tagName);
case 308 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
@@ -23291,6 +23314,18 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "diagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_diagnostic_information
+ },
+ {
+ name: "extendedDiagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_verbose_diagnostic_information
+ },
];
/* @internal */
ts.optionDeclarations = ts.commonOptionsWithBuild.concat([
@@ -23754,18 +23789,6 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
},
- {
- name: "diagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_diagnostic_information
- },
- {
- name: "extendedDiagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_verbose_diagnostic_information
- },
{
name: "resolveJsonModule",
type: "boolean",
@@ -28236,6 +28259,7 @@ var ts;
}
}
function bindJSDocTypeAlias(node) {
+ node.tagName.parent = node;
if (node.fullName) {
setParentPointers(node, node.fullName);
}
@@ -29349,7 +29373,7 @@ var ts;
return true;
}
var node = symbol.valueDeclaration;
- if (ts.isCallExpression(node)) {
+ if (node && ts.isCallExpression(node)) {
return !!ts.getAssignedExpandoInitializer(node);
}
var init = !node ? undefined :
@@ -30921,17 +30945,7 @@ var ts;
var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
return parsed ? isImplementationOfOverload(parsed) : undefined;
},
- getImmediateAliasedSymbol: function (symbol) {
- ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
- var links = getSymbolLinks(symbol);
- if (!links.immediateTarget) {
- var node = getDeclarationOfAliasSymbol(symbol);
- if (!node)
- return ts.Debug.fail();
- links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
- }
- return links.immediateTarget;
- },
+ getImmediateAliasedSymbol: getImmediateAliasedSymbol,
getAliasedSymbol: resolveAlias,
getEmitResolver: getEmitResolver,
getExportsOfModule: getExportsOfModuleAsArray,
@@ -30961,6 +30975,7 @@ var ts;
getNumberType: function () { return numberType; },
createPromiseType: createPromiseType,
createArrayType: createArrayType,
+ getElementTypeOfArrayType: getElementTypeOfArrayType,
getBooleanType: function () { return booleanType; },
getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
@@ -31510,7 +31525,11 @@ var ts;
(source.flags | target.flags) & 67108864 /* Assignment */) {
ts.Debug.assert(source !== target);
if (!(target.flags & 33554432 /* Transient */)) {
- target = cloneSymbol(resolveSymbol(target));
+ var resolvedTarget = resolveSymbol(target);
+ if (resolvedTarget === unknownSymbol) {
+ return source;
+ }
+ target = cloneSymbol(resolvedTarget);
}
// Javascript static-property-assignment declarations always merge, even though they are also values
if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
@@ -32769,8 +32788,8 @@ var ts;
undefined;
return initializer || decl;
}
- function resolveExternalModuleName(location, moduleReferenceExpression) {
- return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
+ function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
+ return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0);
}
function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
if (isForAugmentation === void 0) { isForAugmentation = false; }
@@ -32798,7 +32817,7 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
- if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) {
+ if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
}
// merged symbol is module declaration symbol combined with all augmentations
@@ -33069,6 +33088,50 @@ var ts;
function getParentOfSymbol(symbol) {
return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
}
+ function getAlternativeContainingModules(symbol, enclosingDeclaration) {
+ var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
+ var id = "" + getNodeId(containingFile);
+ var links = getSymbolLinks(symbol);
+ var results;
+ if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
+ return results;
+ }
+ if (containingFile && containingFile.imports) {
+ // Try to make an import using an import already in the enclosing file, if possible
+ for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
+ var importRef = _a[_i];
+ if (ts.nodeIsSynthesized(importRef))
+ continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
+ var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
+ if (!resolvedModule)
+ continue;
+ var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, resolvedModule);
+ }
+ if (ts.length(results)) {
+ (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
+ return results;
+ }
+ }
+ if (links.extendedContainers) {
+ return links.extendedContainers;
+ }
+ // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
+ var otherFiles = host.getSourceFiles();
+ for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
+ var file = otherFiles_1[_b];
+ if (!ts.isExternalModule(file))
+ continue;
+ var sym = getSymbolOfNode(file);
+ var ref = getAliasForSymbolInContainer(sym, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, sym);
+ }
+ return links.extendedContainers = results || ts.emptyArray;
+ }
/**
* Attempts to find the symbol corresponding to the container a symbol is in - usually this
* is just its' `.parent`, but for locals, this value is `undefined`
@@ -33077,10 +33140,12 @@ var ts;
var container = getParentOfSymbol(symbol);
if (container) {
var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
+ var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
- return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope
+ return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
}
- return ts.append(additionalContainers, container);
+ var res = ts.append(additionalContainers, container);
+ return ts.concatenate(res, reexportContainers);
}
var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; });
if (!ts.length(candidates)) {
@@ -33519,7 +33584,7 @@ var ts;
}
function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
- var nodeFlags = 3112960 /* IgnoreErrors */;
+ var nodeFlags = 70221824 /* IgnoreErrors */;
if (flags & 2 /* UseOnlyExternalAliasing */) {
nodeFlags |= 128 /* UseOnlyExternalAliasing */;
}
@@ -33530,7 +33595,7 @@ var ts;
nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
}
if (flags & 16 /* DoNotIncludeSymbolChain */) {
- nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */;
+ nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
}
var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
@@ -33553,7 +33618,7 @@ var ts;
else {
sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */;
}
- var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
+ var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217
@@ -33564,7 +33629,7 @@ var ts;
if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
- var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
+ var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
if (typeNode === undefined)
return ts.Debug.fail("should always get typenode");
var options = { removeComments: true };
@@ -33615,7 +33680,7 @@ var ts;
enclosingDeclaration: enclosingDeclaration,
flags: flags || 0 /* None */,
// If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
- tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? {
+ tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
getSourceFiles: function () { return host.getSourceFiles(); },
getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); })
@@ -33868,11 +33933,7 @@ var ts;
return symbolToTypeNode(typeAlias, context, 67897832 /* Type */);
}
else {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
}
else {
@@ -33886,11 +33947,7 @@ var ts;
}
var depth = context.symbolDepth.get(id) || 0;
if (depth > 10) {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
context.symbolDepth.set(id, depth + 1);
context.visitedTypes.set(typeId, true);
@@ -34075,10 +34132,15 @@ var ts;
typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context));
}
if (resolvedType.stringIndexInfo) {
- var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ?
- createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) :
- resolvedType.stringIndexInfo;
- typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context));
+ var indexSignature = void 0;
+ if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
+ indexSignature.type = createElidedInformationPlaceholder(context);
+ }
+ else {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
+ }
+ typeElements.push(indexSignature);
}
if (resolvedType.numberIndexInfo) {
typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
@@ -34109,8 +34171,16 @@ var ts;
return typeElements.length ? typeElements : undefined;
}
}
+ function createElidedInformationPlaceholder(context) {
+ context.approximateLength += 3;
+ if (!(context.flags & 1 /* NoTruncation */)) {
+ return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
+ }
+ return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
function addPropertyToElementList(propertySymbol, context, typeElements) {
- var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ?
+ var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */);
+ var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
anyType : getTypeOfSymbol(propertySymbol);
var saveEnclosingDeclaration = context.enclosingDeclaration;
context.enclosingDeclaration = undefined;
@@ -34140,8 +34210,14 @@ var ts;
}
else {
var savedFlags = context.flags;
- context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0;
- var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
+ var propertyTypeNode = void 0;
+ if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
+ propertyTypeNode = createElidedInformationPlaceholder(context);
+ }
+ else {
+ propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
context.flags = savedFlags;
var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined;
if (modifiers) {
@@ -34327,7 +34403,7 @@ var ts;
// Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
var chain;
var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
- if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) {
+ if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
ts.Debug.assert(chain && chain.length > 0);
}
@@ -34338,13 +34414,22 @@ var ts;
/** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
function getSymbolChain(symbol, meaning, endOfChain) {
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
+ var parentSpecifiers;
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
// Go up and add our parent.
- var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
- if (ts.length(parents)) {
- for (var _i = 0, _a = parents; _i < _a.length; _i++) {
- var parent = _a[_i];
+ var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
+ if (ts.length(parents_1)) {
+ parentSpecifiers = parents_1.map(function (symbol) {
+ return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
+ ? getSpecifierForModuleSymbol(symbol, context)
+ : undefined;
+ });
+ var indices = parents_1.map(function (_, i) { return i; });
+ indices.sort(sortByBestName);
+ var sortedParents = indices.map(function (i) { return parents_1[i]; });
+ for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
+ var parent = sortedParents_1[_i];
var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
if (parentChain) {
accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
@@ -34367,6 +34452,24 @@ var ts;
}
return [symbol];
}
+ function sortByBestName(a, b) {
+ var specifierA = parentSpecifiers[a];
+ var specifierB = parentSpecifiers[b];
+ if (specifierA && specifierB) {
+ var isBRelative = ts.pathIsRelative(specifierB);
+ if (ts.pathIsRelative(specifierA) === isBRelative) {
+ // Both relative or both non-relative, sort by number of parts
+ return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
+ }
+ if (isBRelative) {
+ // A is non-relative, B is relative: prefer A
+ return -1;
+ }
+ // A is relative, B is non-relative: prefer B
+ return 1;
+ }
+ return 0;
+ }
}
}
function typeParametersToTypeParameterDeclarations(symbol, context) {
@@ -34455,6 +34558,14 @@ var ts;
var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
var specifier = getSpecifierForModuleSymbol(chain[0], context);
+ if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
+ // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
+ // since declaration files with these kinds of references are liable to fail when published :(
+ context.encounteredError = true;
+ if (context.tracker.reportLikelyUnsafeImportRequiredError) {
+ context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
+ }
+ }
var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
@@ -34591,7 +34702,7 @@ var ts;
if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
function typePredicateToStringWorker(writer) {
- var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
+ var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
var printer = ts.createPrinter({ removeComments: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
@@ -36016,7 +36127,7 @@ var ts;
return type.resolvedBaseTypes = ts.emptyArray;
}
if (!isValidBaseType(baseType)) {
- error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType));
+ error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType));
return type.resolvedBaseTypes = ts.emptyArray;
}
if (type === baseType || hasBaseType(baseType, type)) {
@@ -36072,7 +36183,7 @@ var ts;
}
}
else {
- error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface);
+ error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -39372,7 +39483,7 @@ var ts;
if (accessExpression) {
markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */);
if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) {
- error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop));
+ error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
return missingType;
}
if (cacheSymbol) {
@@ -41636,7 +41747,8 @@ var ts;
var bestMatchingType = findMatchingDiscriminantType(source, target) ||
findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
findBestTypeForObjectLiteral(source, target) ||
- findBestTypeForInvokable(source, target);
+ findBestTypeForInvokable(source, target) ||
+ findMostOverlappyType(source, target);
isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
}
return 0 /* False */;
@@ -41671,6 +41783,34 @@ var ts;
return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
}
}
+ function findMostOverlappyType(source, unionTarget) {
+ var bestMatch;
+ var matchingCount = 0;
+ for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
+ var target_1 = _a[_i];
+ var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]);
+ if (overlap.flags & 4194304 /* Index */) {
+ // perfect overlap of keys
+ bestMatch = target_1;
+ matchingCount = Infinity;
+ }
+ else if (overlap.flags & 1048576 /* Union */) {
+ // Some subset overlap if we have only string literals.
+ // If we have a union of index types, it seems likely that we
+ // needed to elaborate between two generic mapped types anyway.
+ var len = ts.length(overlap.types);
+ if (len >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = len;
+ }
+ }
+ else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = 1;
+ }
+ }
+ return bestMatch;
+ }
// Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
function findMatchingDiscriminantType(source, target) {
if (target.flags & 1048576 /* Union */) {
@@ -42773,12 +42913,8 @@ var ts;
return true;
}
// A source signature partially matches a target signature if the target signature has no fewer required
- // parameters and no more overall parameters than the source signature (where a signature with a rest
- // parameter is always considered to have more overall parameters than one without).
- var sourceRestCount = sourceHasRestParameter ? 1 : 0;
- var targetRestCount = targetHasRestParameter ? 1 : 0;
- if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount ||
- sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) {
+ // parameters
+ if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
return true;
}
return false;
@@ -42884,6 +43020,9 @@ var ts;
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
}
+ function getElementTypeOfArrayType(type) {
+ return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined;
+ }
function isArrayLikeType(type) {
// A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
// or if it is not the undefined or null type and if it is assignable to ReadonlyArray
@@ -43256,6 +43395,16 @@ var ts;
diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
break;
case 151 /* Parameter */:
+ var param = declaration;
+ if (ts.isIdentifier(param.name) &&
+ (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
+ param.parent.parameters.indexOf(param) > -1 &&
+ (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
+ param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
+ var newName = "arg" + param.parent.parameters.indexOf(param);
+ errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
+ return;
+ }
diagnostic = declaration.dotDotDotToken ?
noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage :
noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
@@ -45657,7 +45806,12 @@ var ts;
return errorType;
}
if (isReadonlySymbol(localOrExportSymbol)) {
- error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol));
+ if (localOrExportSymbol.flags & 3 /* Variable */) {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
+ }
+ else {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
+ }
return errorType;
}
}
@@ -47142,6 +47296,17 @@ var ts;
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
return createIndexInfo(unionType, /*isReadonly*/ false);
}
+ function getImmediateAliasedSymbol(symbol) {
+ ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
+ var links = getSymbolLinks(symbol);
+ if (!links.immediateTarget) {
+ var node = getDeclarationOfAliasSymbol(symbol);
+ if (!node)
+ return ts.Debug.fail();
+ links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
+ }
+ return links.immediateTarget;
+ }
function checkObjectLiteral(node, checkMode) {
var inDestructuringPattern = ts.isAssignmentTarget(node);
// Grammar checking
@@ -47609,16 +47774,31 @@ var ts;
function getJsxElementChildrenPropertyName(jsxNamespace) {
return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
- function getUninstantiatedJsxSignaturesOfType(elementType) {
+ function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
+ if (elementType.flags & 4 /* String */) {
+ return [anySignature];
+ }
+ else if (elementType.flags & 128 /* StringLiteral */) {
+ var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
+ if (!intrinsicType) {
+ error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
+ return ts.emptyArray;
+ }
+ else {
+ var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
+ return [fakeSignature];
+ }
+ }
+ var apparentElemType = getApparentType(elementType);
// Resolve the signatures, preferring constructor
- var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
+ var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
if (signatures.length === 0) {
// No construct signatures, try call signatures
- signatures = getSignaturesOfType(elementType, 0 /* Call */);
+ signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
}
- if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) {
+ if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
// If each member has some combination of new/call signatures; make a union signature list for those
- signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType));
+ signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
}
return signatures;
}
@@ -47991,7 +48171,7 @@ var ts;
checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop);
if (assignmentKind) {
if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) {
- error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right));
+ error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
return errorType;
}
}
@@ -49559,20 +49739,8 @@ var ts;
if (apparentType === errorType) {
return resolveErrorCall(node);
}
- if (exprTypes.flags & 128 /* StringLiteral */) {
- var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node);
- if (!intrinsicType) {
- error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements);
- return resolveUntypedCall(node);
- }
- else {
- var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes);
- return fakeSignature;
- }
- }
- var signatures = getUninstantiatedJsxSignaturesOfType(apparentType);
- if (exprTypes.flags & 4 /* String */ || isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
+ var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
+ if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
return resolveUntypedCall(node);
}
if (signatures.length === 0) {
@@ -51197,8 +51365,17 @@ var ts;
leftType;
case 59 /* EqualsToken */:
var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
- checkAssignmentDeclaration(declKind, right);
+ checkAssignmentDeclaration(declKind, rightType);
if (isAssignmentDeclaration(declKind)) {
+ if (!(rightType.flags & 524288 /* Object */) ||
+ declKind !== 2 /* ModuleExports */ &&
+ declKind !== 6 /* Prototype */ &&
+ !isEmptyObjectType(rightType) &&
+ !isFunctionObjectType(rightType) &&
+ !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
+ // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
+ checkAssignmentOperator(rightType);
+ }
return leftType;
}
else {
@@ -51213,10 +51390,9 @@ var ts;
default:
return ts.Debug.fail();
}
- function checkAssignmentDeclaration(kind, right) {
+ function checkAssignmentDeclaration(kind, rightType) {
if (kind === 2 /* ModuleExports */) {
- var rightType_1 = checkExpression(right, checkMode);
- for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
var prop = _a[_i];
var propType = getTypeOfSymbol(prop);
if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
@@ -53281,7 +53457,7 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
- if (produceDiagnostics) {
+ if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
@@ -53302,9 +53478,6 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 241 /* InterfaceDeclaration */:
- checkUnusedTypeParameters(node, addDiagnostic);
- break;
case 279 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
@@ -53321,7 +53494,7 @@ var ts;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- if (node.body) {
+ if (node.body) { // Don't report unused parameters in overloads
checkUnusedLocalsAndParameters(node, addDiagnostic);
}
checkUnusedTypeParameters(node, addDiagnostic);
@@ -53332,9 +53505,12 @@ var ts;
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 242 /* TypeAliasDeclaration */:
- case 176 /* InferType */:
+ case 241 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 176 /* InferType */:
+ checkUnusedInferTypeParameter(node, addDiagnostic);
+ break;
default:
ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
}
@@ -53349,77 +53525,73 @@ var ts;
return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
}
function checkUnusedClassMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
- var member = _a[_i];
- switch (member.kind) {
- case 156 /* MethodDeclaration */:
- case 154 /* PropertyDeclaration */:
- case 158 /* GetAccessor */:
- case 159 /* SetAccessor */:
- if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
- // Already would have reported an error on the getter.
- break;
- }
- var symbol = getSymbolOfNode(member);
- if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
- addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
- }
+ for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ switch (member.kind) {
+ case 156 /* MethodDeclaration */:
+ case 154 /* PropertyDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
+ // Already would have reported an error on the getter.
break;
- case 157 /* Constructor */:
- for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
- var parameter = _c[_b];
- if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
- addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
- }
+ }
+ var symbol = getSymbolOfNode(member);
+ if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
+ addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
+ }
+ break;
+ case 157 /* Constructor */:
+ for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
+ var parameter = _c[_b];
+ if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
+ addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
}
- break;
- case 162 /* IndexSignature */:
- case 217 /* SemicolonClassElement */:
- // Can't be private
- break;
- default:
- ts.Debug.fail();
- }
+ }
+ break;
+ case 162 /* IndexSignature */:
+ case 217 /* SemicolonClassElement */:
+ // Can't be private
+ break;
+ default:
+ ts.Debug.fail();
}
}
}
+ function checkUnusedInferTypeParameter(node, addDiagnostic) {
+ var typeParameter = node.typeParameter;
+ if (isTypeParameterUnused(typeParameter)) {
+ addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ }
+ }
function checkUnusedTypeParameters(node, addDiagnostic) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
- if (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node)
+ if (ts.last(getSymbolOfNode(node).declarations) !== node)
return;
- if (node.kind === 176 /* InferType */) {
- var typeParameter = node.typeParameter;
- if (isTypeParameterUnused(typeParameter)) {
- addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
+ var seenParentsWithEveryUnused = new ts.NodeSet();
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var typeParameter = typeParameters_2[_i];
+ if (!isTypeParameterUnused(typeParameter))
+ continue;
+ var name = ts.idText(typeParameter.name);
+ var parent = typeParameter.parent;
+ if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
+ if (seenParentsWithEveryUnused.tryAdd(parent)) {
+ var range = ts.isJSDocTemplateTag(parent)
+ // Whole @template tag
+ ? ts.rangeOfNode(parent)
+ // Include the `<>` in the error message
+ : ts.rangeOfTypeParameters(parent.typeParameters);
+ var only = typeParameters.length === 1;
+ var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
+ var arg0 = only ? name : undefined;
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
+ }
}
- }
- else {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
- if (!isTypeParameterUnused(typeParameter))
- continue;
- var name = ts.idText(typeParameter.name);
- var parent = typeParameter.parent;
- if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
- if (seenParentsWithEveryUnused.tryAdd(parent)) {
- var range = ts.isJSDocTemplateTag(parent)
- // Whole @template tag
- ? ts.rangeOfNode(parent)
- // Include the `<>` in the error message
- : ts.rangeOfTypeParameters(parent.typeParameters);
- var only = typeParameters.length === 1;
- var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
- var arg0 = only ? name : undefined;
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
- }
- }
- else {
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
- }
+ else {
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
}
}
}
@@ -53840,9 +54012,9 @@ var ts;
var nameText = ts.getTextOfPropertyName(name);
if (nameText) {
var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217
- markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
- if (parent.initializer && property) {
- checkPropertyAccessibility(parent, parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
+ if (property) {
+ markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
+ checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
}
}
}
@@ -54900,7 +55072,7 @@ var ts;
}
}
else {
- error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface);
+ error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -56506,7 +56678,10 @@ var ts;
}
if (isDeclarationNameOrImportPropertyName(node)) {
// This is a declaration, call getSymbolOfNode
- return getSymbolOfNode(parent);
+ var parentSymbol = getSymbolOfNode(parent);
+ return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
+ ? getImmediateAliasedSymbol(parentSymbol)
+ : parentSymbol;
}
else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
return getSymbolOfNode(parent.parent);
@@ -64714,7 +64889,7 @@ var ts;
};
function processMapping(mapping) {
var generatedPosition = generatedFile !== undefined
- ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
: -1;
var source;
var sourcePosition;
@@ -64723,7 +64898,7 @@ var ts;
var sourceFile = host.getSourceFileLike(sourceFilePath);
source = map.sources[mapping.sourceIndex];
sourcePosition = sourceFile !== undefined
- ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
: -1;
}
return {
@@ -79713,6 +79888,7 @@ var ts;
reportInaccessibleThisError: reportInaccessibleThisError,
reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
+ reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
moduleResolverHost: host,
trackReferencedAmbientModule: trackReferencedAmbientModule,
trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode
@@ -79801,6 +79977,11 @@ var ts;
context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
}
}
+ function reportLikelyUnsafeImportRequiredError(specifier) {
+ if (errorNameNode) {
+ context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
+ }
+ }
function transformRoot(node) {
if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
@@ -82788,7 +82969,7 @@ var ts;
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
function emitClassExpression(node) {
@@ -83526,7 +83707,7 @@ var ts;
}
function emitSpreadAssignment(node) {
if (node.expression) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
}
@@ -85496,7 +85677,7 @@ var ts;
var text;
try {
ts.performance.mark("beforeIORead");
- text = system.readFile(fileName, options.charset);
+ text = compilerHost.readFile(fileName);
ts.performance.mark("afterIORead");
ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
@@ -85522,7 +85703,12 @@ var ts;
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
- system.createDirectory(directoryPath);
+ if (compilerHost.createDirectory) {
+ compilerHost.createDirectory(directoryPath);
+ }
+ else {
+ system.createDirectory(directoryPath);
+ }
}
}
var outputFingerprints;
@@ -85574,7 +85760,7 @@ var ts;
}
var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
var realpath = system.realpath && (function (path) { return system.realpath(path); });
- return {
+ var compilerHost = {
getSourceFile: getSourceFile,
getDefaultLibLocation: getDefaultLibLocation,
getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
@@ -85590,10 +85776,113 @@ var ts;
getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return system.getDirectories(path); },
realpath: realpath,
- readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }
+ readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
+ createDirectory: function (d) { return system.createDirectory(d); }
};
+ return compilerHost;
}
ts.createCompilerHostWorker = createCompilerHostWorker;
+ /*@internal*/
+ function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) {
+ var originalReadFile = host.readFile;
+ var originalFileExists = host.fileExists;
+ var originalDirectoryExists = host.directoryExists;
+ var originalCreateDirectory = host.createDirectory;
+ var originalWriteFile = host.writeFile;
+ var originalGetSourceFile = host.getSourceFile;
+ var readFileCache = ts.createMap();
+ var fileExistsCache = ts.createMap();
+ var directoryExistsCache = ts.createMap();
+ var sourceFileCache = ts.createMap();
+ var readFileWithCache = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value || undefined;
+ return setReadFileCache(key, fileName);
+ };
+ var setReadFileCache = function (key, fileName) {
+ var newValue = originalReadFile.call(host, fileName);
+ readFileCache.set(key, newValue || false);
+ return newValue;
+ };
+ host.readFile = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value; // could be .d.ts from output
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return originalReadFile.call(host, fileName);
+ }
+ return setReadFileCache(key, fileName);
+ };
+ if (useCacheForSourceFile) {
+ host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
+ var key = toPath(fileName);
+ var value = sourceFileCache.get(key);
+ if (value)
+ return value;
+ var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile);
+ if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
+ sourceFileCache.set(key, sourceFile);
+ }
+ return sourceFile;
+ };
+ }
+ // fileExists for any kind of extension
+ host.fileExists = function (fileName) {
+ var key = toPath(fileName);
+ var value = fileExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalFileExists.call(host, fileName);
+ fileExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
+ var key = toPath(fileName);
+ fileExistsCache.delete(key);
+ var value = readFileCache.get(key);
+ if (value && value !== data) {
+ readFileCache.delete(key);
+ sourceFileCache.delete(key);
+ }
+ else if (useCacheForSourceFile) {
+ var sourceFile = sourceFileCache.get(key);
+ if (sourceFile && sourceFile.text !== data) {
+ sourceFileCache.delete(key);
+ }
+ }
+ originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
+ };
+ // directoryExists
+ if (originalDirectoryExists && originalCreateDirectory) {
+ host.directoryExists = function (directory) {
+ var key = toPath(directory);
+ var value = directoryExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalDirectoryExists.call(host, directory);
+ directoryExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.createDirectory = function (directory) {
+ var key = toPath(directory);
+ directoryExistsCache.delete(key);
+ originalCreateDirectory.call(host, directory);
+ };
+ }
+ return {
+ originalReadFile: originalReadFile,
+ originalFileExists: originalFileExists,
+ originalDirectoryExists: originalDirectoryExists,
+ originalCreateDirectory: originalCreateDirectory,
+ originalWriteFile: originalWriteFile,
+ originalGetSourceFile: originalGetSourceFile,
+ readFileWithCache: readFileWithCache
+ };
+ }
+ ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache;
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (ts.getEmitDeclarations(program.getCompilerOptions())) {
@@ -85980,6 +86269,7 @@ var ts;
// A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
var resolvedProjectReferences;
var projectReferenceRedirects;
+ var mapFromFileToProjectReferenceRedirects;
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2 /* Completely */) {
@@ -87338,15 +87628,20 @@ var ts;
* Get the referenced project if the file is input file from that reference project
*/
function getResolvedProjectReferenceToRedirect(fileName) {
- return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
- // not input file from the referenced project, ignore
- if (!referencedProject ||
- toPath(options.configFilePath) === referenceProjectPath ||
- !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) {
- return undefined;
- }
- return referencedProject;
- });
+ if (mapFromFileToProjectReferenceRedirects === undefined) {
+ mapFromFileToProjectReferenceRedirects = ts.createMap();
+ forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
+ // not input file from the referenced project, ignore
+ if (referencedProject &&
+ toPath(options.configFilePath) !== referenceProjectPath) {
+ referencedProject.commandLine.fileNames.forEach(function (f) {
+ return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
+ });
+ }
+ });
+ }
+ var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
+ return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
}
function forEachResolvedProjectReference(cb) {
return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
@@ -89709,6 +90004,7 @@ var ts;
}
return count;
}
+ moduleSpecifiers.countPathComponents = countPathComponents;
function usesJsExtensionOnImports(_a) {
var imports = _a.imports;
return ts.firstDefined(imports, function (_a) {
@@ -90916,6 +91212,7 @@ var ts;
var missingRoots = ts.createMap();
var globalDependencyGraph;
var writeFileName = function (s) { return host.trace && host.trace(s); };
+ var readFileWithCache = function (f) { return host.readFile(f); };
// Watch state
var diagnostics = createFileMap(toPath);
var projectPendingBuild = createFileMap(toPath);
@@ -91451,19 +91748,15 @@ var ts;
options: configFile.options,
configFileParsingDiagnostics: configFile.errors
};
+ if (host.beforeCreateProgram) {
+ host.beforeCreateProgram(options);
+ }
var program = ts.createProgram(programOptions);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
}
- // Don't emit .d.ts if there are decl file errors
- if (ts.getEmitDeclarations(program.getCompilerOptions())) {
- var declDiagnostics = program.getDeclarationDiagnostics();
- if (declDiagnostics.length) {
- return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
- }
- }
// Same as above but now for semantic diagnostics
var semanticDiagnostics = program.getSemanticDiagnostics();
if (semanticDiagnostics.length) {
@@ -91471,27 +91764,37 @@ var ts;
}
var newestDeclarationFileContentChangedTime = minimumDate;
var anyDtsChanged = false;
- var emitDiagnostics;
- var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); };
- ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) {
+ var declDiagnostics;
+ var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
+ var outputFiles = [];
+ ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); });
+ // Don't emit .d.ts if there are decl file errors
+ if (declDiagnostics) {
+ return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
+ }
+ // Actual Emit
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
var priorChangeTime;
- if (!anyDtsChanged && isDeclarationFile(fileName)) {
+ if (!anyDtsChanged && isDeclarationFile(name)) {
// Check for unchanged .d.ts files
- if (host.fileExists(fileName) && host.readFile(fileName) === content) {
- priorChangeTime = host.getModifiedTime(fileName);
+ if (host.fileExists(name) && readFileWithCache(name) === text) {
+ priorChangeTime = host.getModifiedTime(name);
}
else {
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
anyDtsChanged = true;
}
}
- host.writeFile(fileName, content, writeBom, onError, ts.emptyArray);
+ ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark);
if (priorChangeTime !== undefined) {
newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
- unchangedOutputs.setValue(fileName, priorChangeTime);
+ unchangedOutputs.setValue(name, priorChangeTime);
}
});
- if (emitDiagnostics) {
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
}
var status = {
@@ -91500,11 +91803,17 @@ var ts;
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
}
}
@@ -91571,11 +91880,16 @@ var ts;
if (options.watch) {
reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode);
}
+ // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api
+ // Override readFile for json files and output .d.ts to cache the text
+ var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache;
+ var savedReadFileWithCache = readFileWithCache;
+ readFileWithCache = newReadFileWithCache;
var graph = getGlobalDependencyGraph();
reportBuildQueue(graph);
var anyFailed = false;
- for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
- var next = _a[_i];
+ for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) {
+ var next = _b[_i];
var proj = parseConfigFile(next);
if (proj === undefined) {
reportParseConfigFileDiagnostic(next);
@@ -91617,6 +91931,13 @@ var ts;
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
+ host.readFile = originalReadFile;
+ host.fileExists = originalFileExists;
+ host.directoryExists = originalDirectoryExists;
+ host.createDirectory = originalCreateDirectory;
+ host.writeFile = originalWriteFile;
+ readFileWithCache = savedReadFileWithCache;
+ host.getSourceFile = originalGetSourceFile;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
function reportParseConfigFileDiagnostic(proj) {
@@ -91899,12 +92220,6 @@ var ts;
})(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {}));
/* @internal */
ts.emptyOptions = {};
- var TextChange = /** @class */ (function () {
- function TextChange() {
- }
- return TextChange;
- }());
- ts.TextChange = TextChange;
var HighlightSpanKind;
(function (HighlightSpanKind) {
HighlightSpanKind["none"] = "none";
@@ -92368,6 +92683,10 @@ var ts;
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
ts.isLabelName = isLabelName;
+ function isTagName(node) {
+ return ts.isJSDocTag(node.parent) && node.parent.tagName === node;
+ }
+ ts.isTagName = isTagName;
function isRightSideOfQualifiedName(node) {
return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node;
}
@@ -93258,6 +93577,7 @@ var ts;
ts.createTextChange = createTextChange;
ts.typeKeywords = [
120 /* AnyKeyword */,
+ 146 /* BigIntKeyword */,
123 /* BooleanKeyword */,
87 /* FalseKeyword */,
129 /* KeyOfKeyword */,
@@ -93691,9 +94011,7 @@ var ts;
}
ts.signatureToDisplayParts = signatureToDisplayParts;
function isImportOrExportSpecifierName(location) {
- return !!location.parent &&
- (location.parent.kind === 253 /* ImportSpecifier */ || location.parent.kind === 257 /* ExportSpecifier */) &&
- location.parent.propertyName === location;
+ return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location;
}
ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
/**
@@ -95115,26 +95433,21 @@ var ts;
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
*/
- function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) {
+ function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) {
// Make all paths absolute/normalized if they are not already
rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); });
// Determine the path to the directory containing the script relative to the root directory it is contained within
var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) {
- return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined;
+ return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined;
}); // TODO: GH#18217
// Now find a path for each potential directory that is to be merged with the one containing the script
- return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
}
- function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensionOptions, compilerOptions, host, exclude) {
+ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) {
var basePath = compilerOptions.project || host.getCurrentDirectory();
var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
- var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase);
- var result = [];
- for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) {
- var baseDirectory = baseDirectories_1[_i];
- getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude, result);
- }
- return result;
+ var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
+ return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); });
}
/**
* Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
@@ -96365,7 +96678,8 @@ var ts;
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
isInSnippetScope = isSnippetScope(scopeNode);
- var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
+ var isTypeOnly = isTypeOnlyCompletion();
+ var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) {
@@ -96414,9 +96728,9 @@ var ts;
}
}
function filterGlobalCompletion(symbols) {
- var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
- var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
- if (isTypeOnlyCompletion)
+ var isTypeOnly = isTypeOnlyCompletion();
+ var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
+ if (isTypeOnly)
keywordFilters = 6 /* TypeKeywords */;
ts.filterMutate(symbols, function (symbol) {
if (!ts.isSourceFile(location)) {
@@ -96432,7 +96746,7 @@ var ts;
if (allowTypes) {
// Its a type, but you can reach it by namespace.type as well
var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol);
- if (symbolAllowedAsType || isTypeOnlyCompletion) {
+ if (symbolAllowedAsType || isTypeOnly) {
return symbolAllowedAsType;
}
}
@@ -96441,6 +96755,9 @@ var ts;
return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */);
});
}
+ function isTypeOnlyCompletion() {
+ return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
+ }
function isContextTokenValueLocation(contextToken) {
return contextToken &&
contextToken.kind === 104 /* TypeOfKeyword */ &&
@@ -96826,6 +97143,7 @@ var ts;
if (contextToken) {
var parent = contextToken.parent;
switch (contextToken.kind) {
+ case 30 /* GreaterThanToken */: // End of a type argument list
case 29 /* LessThanSlashToken */:
case 42 /* SlashToken */:
case 72 /* Identifier */:
@@ -96834,6 +97152,11 @@ var ts;
case 267 /* JsxAttribute */:
case 269 /* JsxSpreadAttribute */:
if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) {
+ if (contextToken.kind === 30 /* GreaterThanToken */) {
+ var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined);
+ if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */))
+ break;
+ }
return parent;
}
else if (parent.kind === 267 /* JsxAttribute */) {
@@ -98252,7 +98575,7 @@ var ts;
return undefined;
}
var lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
- return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false };
+ return { kind: 0 /* Import */, symbol: lhsSymbol };
}
else {
return exportInfo(symbol, getExportKindForDeclaration(exportNode));
@@ -98322,7 +98645,7 @@ var ts;
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
- return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
+ return { kind: 0 /* Import */, symbol: importedSymbol };
}
}
function exportInfo(symbol, kind) {
@@ -98367,18 +98690,16 @@ var ts;
var parent = node.parent;
switch (parent.kind) {
case 248 /* ImportEqualsDeclaration */:
- return parent.name === node && isExternalModuleImportEquals(parent)
- ? { isNamedImport: false }
- : undefined;
+ return parent.name === node && isExternalModuleImportEquals(parent);
case 253 /* ImportSpecifier */:
// For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
- return parent.propertyName ? undefined : { isNamedImport: true };
+ return !parent.propertyName;
case 250 /* ImportClause */:
case 251 /* NamespaceImport */:
ts.Debug.assert(parent.name === node);
- return { isNamedImport: false };
+ return true;
default:
- return undefined;
+ return false;
}
}
function getExportInfo(exportSymbol, exportKind, checker) {
@@ -98496,7 +98817,7 @@ var ts;
}
}
function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) {
- return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); });
+ return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); });
}
FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries;
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
@@ -98550,8 +98871,8 @@ var ts;
var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
return { displayParts: displayParts, kind: symbolKind };
}
- function toRenameLocation(entry, originalNode) {
- return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode));
+ function toRenameLocation(entry, originalNode, checker) {
+ return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker));
}
FindAllReferences.toRenameLocation = toRenameLocation;
function toReferenceEntry(entry) {
@@ -98580,25 +98901,27 @@ var ts;
return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName };
}
}
- function getPrefixAndSuffixText(entry, originalNode) {
+ function getPrefixAndSuffixText(entry, originalNode, checker) {
if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) {
var node = entry.node, kind = entry.kind;
var name = originalNode.text;
var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent);
if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) {
- if (kind === 3 /* SearchedLocalFoundProperty */) {
- return { prefixText: name + ": " };
- }
- else if (kind === 4 /* SearchedPropertyFoundLocal */) {
- return { suffixText: ": " + name };
- }
- else {
- return isShorthandAssignment
+ var prefixColon = { prefixText: name + ": " };
+ var suffixColon = { suffixText: ": " + name };
+ return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon
+ : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon
// In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol.
- ? { suffixText: ": " + name }
// For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol.
- : { prefixText: name + ": " };
- }
+ : isShorthandAssignment ? suffixColon : prefixColon;
+ }
+ else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
+ // If the original symbol was using this alias, just rename the alias.
+ var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
+ return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions;
+ }
+ else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
+ return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name };
}
}
return ts.emptyOptions;
@@ -98853,13 +99176,18 @@ var ts;
return undefined;
}
/** Core find-all-references algorithm for a normal symbol. */
- function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
- symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
+ function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
+ var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol;
// Compute the meaning from the location and the symbol it references
var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
var result = [];
var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
- if (node && node.kind === 80 /* DefaultKeyword */) {
+ var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier);
+ if (exportSpecifier) {
+ // When renaming at an export specifier, rename the export and not the thing being exported.
+ getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true);
+ }
+ else if (node && node.kind === 80 /* DefaultKeyword */) {
addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
@@ -98897,15 +99225,11 @@ var ts;
}
}
/** Handle a few special cases relating to export/import specifiers. */
- function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) {
+ function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) {
var parent = node.parent;
- if (ts.isExportSpecifier(parent)) {
+ if (ts.isExportSpecifier(parent) && !isForRename) {
return getLocalSymbolForExportSpecifier(node, symbol, parent, checker);
}
- if (ts.isImportSpecifier(parent) && parent.propertyName === node) {
- // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import.
- return checker.getImmediateAliasedSymbol(symbol);
- }
// If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references.
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
@@ -99068,7 +99392,8 @@ var ts;
var indirectUser = indirectUsers_2[_b];
for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) {
var node = _d[_c];
- if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) {
+ // Import specifiers should be handled by importSearches
+ if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) {
cb(node);
}
}
@@ -99084,7 +99409,7 @@ var ts;
if (!ts.isIdentifier(singleRef))
return false;
// At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */);
+ return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */);
}
// Go to the symbol we imported from and find references for it.
function searchForImportedSymbol(symbol, state) {
@@ -99363,16 +99688,16 @@ var ts;
}
getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
}
- function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) {
+ function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) {
var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
var exportDeclaration = parent.parent;
var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
- if (!search.includes(localSymbol)) {
+ if (!alwaysGetReferences && !search.includes(localSymbol)) {
return;
}
if (!propertyName) {
// Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export)
- if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) {
+ if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) {
addRef();
}
}
@@ -99383,7 +99708,7 @@ var ts;
addRef();
}
if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) {
- addReference(name, referenceSymbol, state);
+ addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state);
}
}
else {
@@ -99392,15 +99717,14 @@ var ts;
}
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
- if (!(referenceLocation === propertyName && state.options.isForRename)) {
+ if (!state.options.isForRename || alwaysGetReferences) {
var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
- var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker);
- if (!exportInfo)
- return ts.Debug.fail();
- searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state);
+ var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
+ var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker));
+ searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
}
// At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
- if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) {
+ if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) {
var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
if (imported)
searchForImportedSymbol(imported, state);
@@ -99432,12 +99756,11 @@ var ts;
return;
var symbol = importOrExport.symbol;
if (importOrExport.kind === 0 /* Import */) {
- if (!state.options.isForRename || importOrExport.isNamedImport) {
+ if (!state.options.isForRename) {
searchForImportedSymbol(symbol, state);
}
}
else {
- // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching.
searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
}
}
@@ -103435,7 +103758,7 @@ var ts;
function getEnclosingDeclarationFromInvocation(invocation) {
return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
}
- var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
+ var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) {
var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
@@ -104601,16 +104924,11 @@ var ts;
this.options = options;
}
FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
- ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null");
- ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null");
- ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null");
- ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null");
- ts.Debug.assert(commonParent !== undefined, "commonParent is null");
- this.currentTokenSpan = currentRange;
- this.currentTokenParent = currentTokenParent;
- this.nextTokenSpan = nextRange;
- this.nextTokenParent = nextTokenParent;
- this.contextNode = commonParent;
+ this.currentTokenSpan = ts.Debug.assertDefined(currentRange);
+ this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent);
+ this.nextTokenSpan = ts.Debug.assertDefined(nextRange);
+ this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent);
+ this.contextNode = ts.Debug.assertDefined(commonParent);
// drop cached results
this.contextNodeAllOnSameLine = undefined;
this.nextNodeAllOnSameLine = undefined;
@@ -107336,7 +107654,6 @@ var ts;
};
ChangeTracker.prototype.deleteRange = function (sourceFile, range) {
this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range });
- return this;
};
ChangeTracker.prototype.delete = function (sourceFile, node) {
this.deletedNodes.push({ sourceFile: sourceFile, node: node });
@@ -107349,7 +107666,6 @@ var ts;
var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
- return this;
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
if (options === void 0) { options = {}; }
@@ -107360,11 +107676,10 @@ var ts;
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
if (options === void 0) { options = {}; }
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
- return this;
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
+ this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
@@ -107373,18 +107688,17 @@ var ts;
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
if (options === void 0) { options = {}; }
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
- return this;
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
+ this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
+ this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
var next = ts.findNextToken(node, node.parent, sourceFile);
@@ -107392,7 +107706,7 @@ var ts;
};
ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
- return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
+ this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
};
ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
if (options === void 0) { options = {}; }
@@ -107641,11 +107955,11 @@ var ts;
if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
- return this;
+ return;
}
var index = ts.indexOfNode(containingList, after);
if (index < 0) {
- return this;
+ return;
}
var end = after.getEnd();
if (index !== containingList.length - 1) {
@@ -107743,7 +108057,6 @@ var ts;
this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
}
}
- return this;
};
ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () {
var _this = this;
@@ -108440,6 +108753,40 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "addNameToNamelessParameter";
+ var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
+ });
+ function makeChange(changeTracker, sourceFile, pos) {
+ var token = ts.getTokenAtPosition(sourceFile, pos);
+ if (!ts.isIdentifier(token)) {
+ return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.formatSyntaxKind(token.kind));
+ }
+ var param = token.parent;
+ if (!ts.isParameter(param)) {
+ return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.formatSyntaxKind(token.kind));
+ }
+ var i = param.parent.parameters.indexOf(param);
+ ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
+ ts.Debug.assert(i > -1, "Parameter not found in parent parameter list.");
+ var replacement = ts.createParameter(
+ /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer);
+ changeTracker.replaceNode(sourceFile, token, replacement);
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -108960,9 +109307,8 @@ var ts;
cancellationToken.throwIfCancellationRequested();
inferTypeFromContext(reference, checker, usageContext);
}
- var isConstructor = declaration.kind === 157 /* Constructor */;
- var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
- return callContexts && declaration.parameters.map(function (parameter, parameterIndex) {
+ var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []);
+ return declaration.parameters.map(function (parameter, parameterIndex) {
var types = [];
var isRest = ts.isRestParameter(parameter);
var isOptional = false;
@@ -108982,7 +109328,8 @@ var ts;
}
}
if (ts.isIdentifier(parameter.name)) {
- types.push.apply(types, inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken));
+ var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken);
+ types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred));
}
var type = unifyFromContext(types, checker);
return {
@@ -109054,8 +109401,7 @@ var ts;
usageContext.isNumber = true;
break;
case 38 /* PlusToken */:
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
break;
// case SyntaxKind.ExclamationToken:
// no inferences here;
@@ -109117,8 +109463,7 @@ var ts;
usageContext.isString = true;
}
else {
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
}
break;
// AssignmentOperators
@@ -109183,8 +109528,7 @@ var ts;
}
function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) {
if (node === parent.argumentExpression) {
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
return;
}
else {
@@ -109199,18 +109543,48 @@ var ts;
}
}
}
+ function removeLowPriorityInferences(inferences, priorities) {
+ var toRemove = [];
+ for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
+ var i = inferences_1[_i];
+ for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
+ var _b = priorities_1[_a], high = _b.high, low = _b.low;
+ if (high(i)) {
+ ts.Debug.assert(!low(i));
+ toRemove.push(low);
+ }
+ }
+ }
+ return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); });
+ }
function unifyFromContext(inferences, checker, fallback) {
if (fallback === void 0) { fallback = checker.getAnyType(); }
if (!inferences.length)
return fallback;
- var hasNonVacuousType = inferences.some(function (i) { return !(i.flags & (1 /* Any */ | 16384 /* Void */)); });
- var hasNonVacuousNonAnonymousType = inferences.some(function (i) { return !(i.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(i) & 16 /* Anonymous */); });
- var anons = inferences.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; });
- var good = [];
- if (!hasNonVacuousNonAnonymousType && anons.length) {
+ // 1. string or number individually override string | number
+ // 2. non-any, non-void overrides any or void
+ // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types
+ var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]);
+ var priorities = [
+ {
+ high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); },
+ low: function (t) { return t === stringNumber; }
+ },
+ {
+ high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); },
+ low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); }
+ },
+ {
+ high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); },
+ low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); }
+ }
+ ];
+ var good = removeLowPriorityInferences(inferences, priorities);
+ var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; });
+ if (anons.length) {
+ good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); });
good.push(unifyAnonymousTypes(anons, checker));
}
- good.push.apply(good, inferences.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */) && !(hasNonVacuousType && i.flags & (1 /* Any */ | 16384 /* Void */)); }));
return checker.getWidenedType(checker.getUnionType(good));
}
InferFromReference.unifyFromContext = unifyFromContext;
@@ -109258,6 +109632,9 @@ var ts;
if (usageContext.isString) {
types.push(checker.getStringType());
}
+ if (usageContext.isNumberOrString) {
+ types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
+ }
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
@@ -109268,7 +109645,7 @@ var ts;
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
}
if (usageContext.numberIndexContext) {
- return [checker.createArrayType(recur(usageContext.numberIndexContext))];
+ types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
var members_1 = ts.createUnderscoreEscapedMap();
@@ -111432,6 +111809,40 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "addMissingNewOperator";
+ var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, span = context.span;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ return addMissingNewOperator(changes, context.sourceFile, diag);
+ }); },
+ });
+ function addMissingNewOperator(changes, sourceFile, span) {
+ var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression);
+ var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments);
+ changes.replaceNode(sourceFile, call, newExpression);
+ }
+ function findAncestorMatchingSpan(sourceFile, span) {
+ var token = ts.getTokenAtPosition(sourceFile, span.start);
+ var end = ts.textSpanEnd(span);
+ while (token.end < end) {
+ token = token.parent;
+ }
+ return token;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -115010,7 +115421,7 @@ var ts;
// readonly modifier only existed in classLikeDeclaration
var constructor = ts.getFirstConstructorWithBody(container);
if (constructor) {
- updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
}
}
else {
@@ -115063,7 +115474,7 @@ var ts;
isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent,
- originalName: declaration.name,
+ originalName: declaration.name.text,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
@@ -115114,22 +115525,23 @@ var ts;
? changeTracker.insertNodeAfterComma(file, declaration, accessor)
: changeTracker.insertNodeAfter(file, declaration, accessor);
}
- function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) {
if (!constructor.body)
return;
- var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
- var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) {
- return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined;
- });
- ts.forEach(referenceEntries, function (entry) {
- var parent = entry.parent;
- var accessorName = ts.createIdentifier(fieldName.text);
- var node = ts.isBinaryExpression(parent)
- ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
- : ts.isPropertyAccessExpression(parent)
- ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
- : ts.Debug.fail("Unexpected write access token");
- changeTracker.replaceNode(file, parent, node);
+ constructor.body.forEachChild(function recur(node) {
+ if (ts.isElementAccessExpression(node) &&
+ node.expression.kind === 100 /* ThisKeyword */ &&
+ ts.isStringLiteral(node.argumentExpression) &&
+ node.argumentExpression.text === originalName &&
+ ts.isWriteAccess(node)) {
+ changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName));
+ }
+ if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) {
+ changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName));
+ }
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
+ node.forEachChild(recur);
+ }
});
}
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
@@ -117071,7 +117483,7 @@ var ts;
function shouldGetType(sourceFile, node, position) {
switch (node.kind) {
case 72 /* Identifier */:
- return !ts.isLabelName(node);
+ return !ts.isLabelName(node) && !ts.isTagName(node);
case 189 /* PropertyAccessExpression */:
case 148 /* QualifiedName */:
// Don't return quickInfo if inside the comment in `a/**/.b`
@@ -117653,7 +118065,7 @@ var ts;
function initializeNameTable(sourceFile) {
var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap();
sourceFile.forEachChild(function walk(node) {
- if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
+ if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
var text = ts.getEscapedTextOfIdentifierOrLiteral(node);
nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
}
@@ -118567,9 +118979,15 @@ var ts;
if ("directoryExists" in this.shimHost) {
this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
}
+ else {
+ this.directoryExists = undefined; // TODO: GH#18217
+ }
if ("realpath" in this.shimHost) {
this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217
}
+ else {
+ this.realpath = undefined; // TODO: GH#18217
+ }
}
CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) {
var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
@@ -119864,6 +120282,9 @@ var ts;
this.host = host;
this.fileName = fileName;
this.info = info;
+ this.isOpen = false;
+ this.ownFileText = false;
+ this.pendingReloadFromDisk = false;
this.version = initialVersion || { svc: 0, text: 0 };
}
TextStorage.prototype.getVersion = function () {
@@ -119881,6 +120302,7 @@ var ts;
this.svc = undefined;
this.text = newText;
this.lineMap = undefined;
+ this.fileSize = undefined;
this.version.text++;
};
TextStorage.prototype.edit = function (start, end, newText) {
@@ -119888,6 +120310,7 @@ var ts;
this.ownFileText = false;
this.text = undefined;
this.lineMap = undefined;
+ this.fileSize = undefined;
};
TextStorage.prototype.reload = function (newText) {
ts.Debug.assert(newText !== undefined);
@@ -119897,9 +120320,12 @@ var ts;
this.ownFileText = false;
return true;
}
+ return false;
};
TextStorage.prototype.reloadWithFileText = function (tempFileName) {
- var reloaded = this.reload(this.getFileText(tempFileName));
+ var _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize;
+ var reloaded = this.reload(newText);
+ this.fileSize = fileSize;
this.ownFileText = !tempFileName || tempFileName === this.fileName;
return reloaded;
};
@@ -119912,6 +120338,15 @@ var ts;
TextStorage.prototype.delayReloadFromFileIntoText = function () {
this.pendingReloadFromDisk = true;
};
+ TextStorage.prototype.getTelemetryFileSize = function () {
+ return !!this.fileSize
+ ? this.fileSize
+ : !!this.text
+ ? this.text.length
+ : !!this.svc
+ ? this.svc.getSnapshot().getLength()
+ : this.getSnapshot().getLength();
+ };
TextStorage.prototype.getSnapshot = function () {
return this.useScriptVersionCacheIfValidOrOpen()
? this.svc.getSnapshot()
@@ -119942,7 +120377,7 @@ var ts;
}
return this.svc.positionToLineOffset(position);
};
- TextStorage.prototype.getFileText = function (tempFileName) {
+ TextStorage.prototype.getFileTextAndSize = function (tempFileName) {
var _this = this;
var text;
var fileName = tempFileName || this.fileName;
@@ -119954,10 +120389,10 @@ var ts;
var service = this.info.containingProjects[0].projectService;
service.logger.info("Skipped loading contents of large file " + fileName + " for info " + this.info.fileName + ": fileSize: " + fileSize);
this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize);
- return "";
+ return { text: "", fileSize: fileSize };
}
}
- return getText();
+ return { text: getText() };
};
TextStorage.prototype.switchToScriptVersionCache = function () {
if (!this.svc || this.pendingReloadFromDisk) {
@@ -120014,6 +120449,9 @@ var ts;
ScriptInfo.prototype.getVersion = function () {
return this.textStorage.version;
};
+ ScriptInfo.prototype.getTelemetryFileSize = function () {
+ return this.textStorage.getTelemetryFileSize();
+ };
ScriptInfo.prototype.isDynamicOrHasMixedContent = function () {
return this.hasMixedContent || this.isDynamic;
};
@@ -120345,27 +120783,45 @@ var ts;
ProjectKind[ProjectKind["Configured"] = 1] = "Configured";
ProjectKind[ProjectKind["External"] = 2] = "External";
})(ProjectKind = server.ProjectKind || (server.ProjectKind = {}));
- function countEachFileTypes(infos) {
- var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0, deferred: 0 };
+ function countEachFileTypes(infos, includeSizes) {
+ if (includeSizes === void 0) { includeSizes = false; }
+ var result = {
+ js: 0, jsSize: 0,
+ jsx: 0, jsxSize: 0,
+ ts: 0, tsSize: 0,
+ tsx: 0, tsxSize: 0,
+ dts: 0, dtsSize: 0,
+ deferred: 0, deferredSize: 0,
+ };
for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
var info = infos_1[_i];
+ var fileSize = includeSizes ? info.getTelemetryFileSize() : 0;
switch (info.scriptKind) {
case 1:
result.js += 1;
+ result.jsSize += fileSize;
break;
case 2:
result.jsx += 1;
+ result.jsxSize += fileSize;
break;
case 3:
- ts.fileExtensionIs(info.fileName, ".d.ts")
- ? result.dts += 1
- : result.ts += 1;
+ if (ts.fileExtensionIs(info.fileName, ".d.ts")) {
+ result.dts += 1;
+ result.dtsSize += fileSize;
+ }
+ else {
+ result.ts += 1;
+ result.tsSize += fileSize;
+ }
break;
case 4:
result.tsx += 1;
+ result.tsxSize += fileSize;
break;
case 7:
result.deferred += 1;
+ result.deferredSize += fileSize;
break;
}
}
@@ -120839,7 +121295,7 @@ var ts;
return false;
};
Project.prototype.containsScriptInfo = function (info) {
- return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined);
+ return this.isRoot(info) || (!!this.program && this.program.getSourceFileByPath(info.path) !== undefined);
};
Project.prototype.containsFile = function (filename, requireOpen) {
var info = this.projectService.getScriptInfoForNormalizedPath(filename);
@@ -120996,7 +121452,7 @@ var ts;
return fileWatcher;
};
Project.prototype.isWatchedMissingFile = function (path) {
- return this.missingFilesMap && this.missingFilesMap.has(path);
+ return !!this.missingFilesMap && this.missingFilesMap.has(path);
};
Project.prototype.getScriptInfoForNormalizedPath = function (fileName) {
var scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName));
@@ -121284,6 +121740,7 @@ var ts;
__extends(ConfiguredProject, _super);
function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) {
var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, false, undefined, {}, false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
+ _this.canConfigFileJsonReportNoInputFiles = false;
_this.externalProjectRefCount = 0;
_this.isInitialLoadPending = ts.returnTrue;
_this.sendLoadingProjectFinish = false;
@@ -121642,6 +122099,7 @@ var ts;
this.safelist = defaultTypeSafeList;
this.legacySafelist = ts.createMap();
this.pendingProjectUpdates = ts.createMap();
+ this.pendingEnsureProjectForOpenFiles = false;
this.seenProjects = ts.createMap();
this.seenSurveyProjects = ts.createMap();
this.host = opts.host;
@@ -122402,7 +122860,7 @@ var ts;
setProjectOptionsUsed(project);
var data = {
projectId: this.host.createSHA256Hash(project.projectName),
- fileStats: server.countEachFileTypes(project.getScriptInfos()),
+ fileStats: server.countEachFileTypes(project.getScriptInfos(), true),
compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()),
typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()),
extends: projectOptions && projectOptions.configHasExtendsProperty,
@@ -125132,7 +125590,7 @@ var ts;
Session.prototype.isLocation = function (locationOrSpan) {
return locationOrSpan.line !== undefined;
};
- Session.prototype.extractPositionAndRange = function (args, scriptInfo) {
+ Session.prototype.extractPositionOrRange = function (args, scriptInfo) {
var position;
var textRange;
if (this.isLocation(args)) {
@@ -125142,7 +125600,7 @@ var ts;
var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition;
textRange = { pos: startPosition, end: endPosition };
}
- return { position: position, textRange: textRange };
+ return ts.Debug.assertDefined(position === undefined ? textRange : position);
function getPosition(loc) {
return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset);
}
@@ -125150,14 +125608,12 @@ var ts;
Session.prototype.getApplicableRefactors = function (args) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange;
- return project.getLanguageService().getApplicableRefactors(file, position || textRange, this.getPreferences(file));
+ return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file));
};
Session.prototype.getEditsForRefactor = function (args, simplifiedResult) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange;
- var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), position || textRange, args.refactor, args.action, this.getPreferences(file));
+ var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, this.getPreferences(file));
if (result === undefined) {
return {
edits: []
@@ -126345,6 +126801,8 @@ var ts;
this.activeRequestCount = 0;
this.requestQueue = [];
this.requestMap = ts.createMap(); // Maps operation ID to newest requestQueue entry with that ID
+ /** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */
+ this.requestedRegistry = false;
}
NodeTypingsInstaller.prototype.isKnownTypesPackageName = function (name) {
// We want to avoid looking this up in the registry as that is expensive. So first check that it's actually an NPM package.
diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts
index ac36533a094..e67f6d36447 100644
--- a/lib/tsserverlibrary.d.ts
+++ b/lib/tsserverlibrary.d.ts
@@ -1976,7 +1976,8 @@ declare namespace ts {
AllowEmptyTuple = 524288,
AllowUniqueESSymbolType = 1048576,
AllowEmptyIndexInfoType = 2097152,
- IgnoreErrors = 3112960,
+ AllowNodeModulesRelativePaths = 67108864,
+ IgnoreErrors = 70221824,
InObjectTypeLiteral = 4194304,
InTypeAlias = 8388608,
InInitialEntityName = 16777216,
@@ -3131,7 +3132,6 @@ declare namespace ts {
function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean;
function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner;
}
-/** Non-internal stuff goes here */
declare namespace ts {
function isExternalModuleNameRelative(moduleName: string): boolean;
function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray;
@@ -3478,6 +3478,7 @@ declare namespace ts {
type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail;
function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken;
function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail;
+ function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier;
function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken;
function isModifier(node: Node): node is Modifier;
function isEntityName(node: Node): node is EntityName;
@@ -4867,7 +4868,7 @@ declare namespace ts {
message: string;
position: number;
}
- class TextChange {
+ interface TextChange {
span: TextSpan;
newText: string;
}
@@ -8435,11 +8436,17 @@ declare namespace ts.server {
}
interface FileStats {
readonly js: number;
+ readonly jsSize?: number;
readonly jsx: number;
+ readonly jsxSize?: number;
readonly ts: number;
+ readonly tsSize?: number;
readonly tsx: number;
+ readonly tsxSize?: number;
readonly dts: number;
+ readonly dtsSize?: number;
readonly deferred: number;
+ readonly deferredSize?: number;
}
interface OpenFileInfo {
readonly checkJs: boolean;
@@ -8893,7 +8900,7 @@ declare namespace ts.server {
private getFullNavigateToItems;
private getSupportedCodeFixes;
private isLocation;
- private extractPositionAndRange;
+ private extractPositionOrRange;
private getApplicableRefactors;
private getEditsForRefactor;
private organizeImports;
diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js
index 0767cfedaad..d09a87c970d 100644
--- a/lib/tsserverlibrary.js
+++ b/lib/tsserverlibrary.js
@@ -84,7 +84,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "3.2";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".1";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -3060,13 +3060,15 @@ var ts;
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
- NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors";
+ // Errors (cont.)
+ NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
+ /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
+ NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
// State
NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
- /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain";
})(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
// Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
var TypeFormatFlags;
@@ -5258,7 +5260,7 @@ var ts;
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
- An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."),
+ An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
@@ -5365,7 +5367,7 @@ var ts;
Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
- A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."),
+ A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."),
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
@@ -5448,7 +5450,7 @@ var ts;
_0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
- Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."),
+ Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
@@ -5479,7 +5481,7 @@ var ts;
Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
- Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."),
+ Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
@@ -5524,6 +5526,7 @@ var ts;
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
+ Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
@@ -5623,6 +5626,7 @@ var ts;
Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
+ The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
@@ -6018,6 +6022,7 @@ var ts;
Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
+ Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
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."),
@@ -6113,6 +6118,7 @@ var ts;
Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
+ Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
@@ -6181,6 +6187,9 @@ var ts;
Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"),
Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
+ Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
+ Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
+ Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
};
})(ts || (ts = {}));
var ts;
@@ -6410,11 +6419,28 @@ var ts;
}
ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
/* @internal */
- function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) {
+ function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) {
+ return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true);
+ }
+ ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits;
+ /* @internal */
+ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
if (line < 0 || line >= lineStarts.length) {
- ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ if (allowEdits) {
+ // Clamp line to nearest allowable value
+ line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
+ }
+ else {
+ ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ }
}
var res = lineStarts[line] + character;
+ if (allowEdits) {
+ // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
+ // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
+ // apply them to the computed position to improve accuracy
+ return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
+ }
if (line < lineStarts.length - 1) {
ts.Debug.assert(res < lineStarts[line + 1]);
}
@@ -8066,7 +8092,6 @@ var ts;
}
ts.createScanner = createScanner;
})(ts || (ts = {}));
-/** Non-internal stuff goes here */
var ts;
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -12351,6 +12376,31 @@ var ts;
return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
}
ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
+ function isTypeNodeKind(kind) {
+ return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
+ || kind === 120 /* AnyKeyword */
+ || kind === 143 /* UnknownKeyword */
+ || kind === 135 /* NumberKeyword */
+ || kind === 146 /* BigIntKeyword */
+ || kind === 136 /* ObjectKeyword */
+ || kind === 123 /* BooleanKeyword */
+ || kind === 138 /* StringKeyword */
+ || kind === 139 /* SymbolKeyword */
+ || kind === 100 /* ThisKeyword */
+ || kind === 106 /* VoidKeyword */
+ || kind === 141 /* UndefinedKeyword */
+ || kind === 96 /* NullKeyword */
+ || kind === 132 /* NeverKeyword */
+ || kind === 211 /* ExpressionWithTypeArguments */
+ || kind === 284 /* JSDocAllType */
+ || kind === 285 /* JSDocUnknownType */
+ || kind === 286 /* JSDocNullableType */
+ || kind === 287 /* JSDocNonNullableType */
+ || kind === 288 /* JSDocOptionalType */
+ || kind === 289 /* JSDocFunctionType */
+ || kind === 290 /* JSDocVariadicType */;
+ }
+ ts.isTypeNodeKind = isTypeNodeKind;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13819,6 +13869,10 @@ var ts;
|| kind === 17 /* TemplateTail */;
}
ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
+ function isImportOrExportSpecifier(node) {
+ return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
+ }
+ ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
function isStringTextContainingNode(node) {
return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
}
@@ -13987,37 +14041,13 @@ var ts;
}
ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
// Type
- function isTypeNodeKind(kind) {
- return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
- || kind === 120 /* AnyKeyword */
- || kind === 143 /* UnknownKeyword */
- || kind === 135 /* NumberKeyword */
- || kind === 146 /* BigIntKeyword */
- || kind === 136 /* ObjectKeyword */
- || kind === 123 /* BooleanKeyword */
- || kind === 138 /* StringKeyword */
- || kind === 139 /* SymbolKeyword */
- || kind === 100 /* ThisKeyword */
- || kind === 106 /* VoidKeyword */
- || kind === 141 /* UndefinedKeyword */
- || kind === 96 /* NullKeyword */
- || kind === 132 /* NeverKeyword */
- || kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
- }
/**
* Node test that determines whether a node is a valid type node.
* This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
* of a TypeNode.
*/
function isTypeNode(node) {
- return isTypeNodeKind(node.kind);
+ return ts.isTypeNodeKind(node.kind);
}
ts.isTypeNode = isTypeNode;
function isFunctionOrConstructorTypeNode(node) {
@@ -16538,53 +16568,46 @@ var ts;
return visitNodes(cbNode, cbNodes, node.tags);
case 299 /* JSDocParameterTag */:
case 305 /* JSDocPropertyTag */:
- if (node.isNameFirst) {
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.typeExpression);
- }
- else {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.name);
- }
- case 300 /* JSDocReturnTag */:
- return visitNode(cbNode, node.typeExpression);
- case 302 /* JSDocTypeTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ (node.isNameFirst
+ ? visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.typeExpression)
+ : visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.name));
case 295 /* JSDocAugmentsTag */:
- return visitNode(cbNode, node.class);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.class);
case 303 /* JSDocTemplateTag */:
- return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.constraint) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters);
case 304 /* JSDocTypedefTag */:
- if (node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */) {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.fullName);
- }
- else {
- return visitNode(cbNode, node.fullName) ||
- visitNode(cbNode, node.typeExpression);
- }
+ return visitNode(cbNode, node.tagName) ||
+ (node.typeExpression &&
+ node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ ? visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.fullName)
+ : visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression));
case 297 /* JSDocCallbackTag */:
- return visitNode(cbNode, node.fullName) ||
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
+ case 300 /* JSDocReturnTag */:
+ case 302 /* JSDocTypeTag */:
case 301 /* JSDocThisTag */:
- return visitNode(cbNode, node.typeExpression);
case 298 /* JSDocEnumTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.typeExpression);
case 293 /* JSDocSignature */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- ts.forEach(node.typeParameters, cbNode) ||
+ return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
case 292 /* JSDocTypeLiteral */:
- if (node.jsDocPropertyTags) {
- for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
- var tag = _a[_i];
- visitNode(cbNode, tag);
- }
- }
- return;
+ return ts.forEach(node.jsDocPropertyTags, cbNode);
+ case 294 /* JSDocTag */:
+ case 296 /* JSDocClassTag */:
+ return visitNode(cbNode, node.tagName);
case 308 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
@@ -23287,6 +23310,18 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "diagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_diagnostic_information
+ },
+ {
+ name: "extendedDiagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_verbose_diagnostic_information
+ },
];
/* @internal */
ts.optionDeclarations = ts.commonOptionsWithBuild.concat([
@@ -23750,18 +23785,6 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
},
- {
- name: "diagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_diagnostic_information
- },
- {
- name: "extendedDiagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_verbose_diagnostic_information
- },
{
name: "resolveJsonModule",
type: "boolean",
@@ -28232,6 +28255,7 @@ var ts;
}
}
function bindJSDocTypeAlias(node) {
+ node.tagName.parent = node;
if (node.fullName) {
setParentPointers(node, node.fullName);
}
@@ -29345,7 +29369,7 @@ var ts;
return true;
}
var node = symbol.valueDeclaration;
- if (ts.isCallExpression(node)) {
+ if (node && ts.isCallExpression(node)) {
return !!ts.getAssignedExpandoInitializer(node);
}
var init = !node ? undefined :
@@ -30917,17 +30941,7 @@ var ts;
var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
return parsed ? isImplementationOfOverload(parsed) : undefined;
},
- getImmediateAliasedSymbol: function (symbol) {
- ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
- var links = getSymbolLinks(symbol);
- if (!links.immediateTarget) {
- var node = getDeclarationOfAliasSymbol(symbol);
- if (!node)
- return ts.Debug.fail();
- links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
- }
- return links.immediateTarget;
- },
+ getImmediateAliasedSymbol: getImmediateAliasedSymbol,
getAliasedSymbol: resolveAlias,
getEmitResolver: getEmitResolver,
getExportsOfModule: getExportsOfModuleAsArray,
@@ -30957,6 +30971,7 @@ var ts;
getNumberType: function () { return numberType; },
createPromiseType: createPromiseType,
createArrayType: createArrayType,
+ getElementTypeOfArrayType: getElementTypeOfArrayType,
getBooleanType: function () { return booleanType; },
getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
@@ -31506,7 +31521,11 @@ var ts;
(source.flags | target.flags) & 67108864 /* Assignment */) {
ts.Debug.assert(source !== target);
if (!(target.flags & 33554432 /* Transient */)) {
- target = cloneSymbol(resolveSymbol(target));
+ var resolvedTarget = resolveSymbol(target);
+ if (resolvedTarget === unknownSymbol) {
+ return source;
+ }
+ target = cloneSymbol(resolvedTarget);
}
// Javascript static-property-assignment declarations always merge, even though they are also values
if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
@@ -32765,8 +32784,8 @@ var ts;
undefined;
return initializer || decl;
}
- function resolveExternalModuleName(location, moduleReferenceExpression) {
- return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
+ function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
+ return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0);
}
function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
if (isForAugmentation === void 0) { isForAugmentation = false; }
@@ -32794,7 +32813,7 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
- if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) {
+ if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
}
// merged symbol is module declaration symbol combined with all augmentations
@@ -33065,6 +33084,50 @@ var ts;
function getParentOfSymbol(symbol) {
return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
}
+ function getAlternativeContainingModules(symbol, enclosingDeclaration) {
+ var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
+ var id = "" + getNodeId(containingFile);
+ var links = getSymbolLinks(symbol);
+ var results;
+ if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
+ return results;
+ }
+ if (containingFile && containingFile.imports) {
+ // Try to make an import using an import already in the enclosing file, if possible
+ for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
+ var importRef = _a[_i];
+ if (ts.nodeIsSynthesized(importRef))
+ continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
+ var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
+ if (!resolvedModule)
+ continue;
+ var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, resolvedModule);
+ }
+ if (ts.length(results)) {
+ (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
+ return results;
+ }
+ }
+ if (links.extendedContainers) {
+ return links.extendedContainers;
+ }
+ // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
+ var otherFiles = host.getSourceFiles();
+ for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
+ var file = otherFiles_1[_b];
+ if (!ts.isExternalModule(file))
+ continue;
+ var sym = getSymbolOfNode(file);
+ var ref = getAliasForSymbolInContainer(sym, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, sym);
+ }
+ return links.extendedContainers = results || ts.emptyArray;
+ }
/**
* Attempts to find the symbol corresponding to the container a symbol is in - usually this
* is just its' `.parent`, but for locals, this value is `undefined`
@@ -33073,10 +33136,12 @@ var ts;
var container = getParentOfSymbol(symbol);
if (container) {
var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
+ var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
- return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope
+ return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
}
- return ts.append(additionalContainers, container);
+ var res = ts.append(additionalContainers, container);
+ return ts.concatenate(res, reexportContainers);
}
var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; });
if (!ts.length(candidates)) {
@@ -33515,7 +33580,7 @@ var ts;
}
function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
- var nodeFlags = 3112960 /* IgnoreErrors */;
+ var nodeFlags = 70221824 /* IgnoreErrors */;
if (flags & 2 /* UseOnlyExternalAliasing */) {
nodeFlags |= 128 /* UseOnlyExternalAliasing */;
}
@@ -33526,7 +33591,7 @@ var ts;
nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
}
if (flags & 16 /* DoNotIncludeSymbolChain */) {
- nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */;
+ nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
}
var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
@@ -33549,7 +33614,7 @@ var ts;
else {
sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */;
}
- var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
+ var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217
@@ -33560,7 +33625,7 @@ var ts;
if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
- var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
+ var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
if (typeNode === undefined)
return ts.Debug.fail("should always get typenode");
var options = { removeComments: true };
@@ -33611,7 +33676,7 @@ var ts;
enclosingDeclaration: enclosingDeclaration,
flags: flags || 0 /* None */,
// If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
- tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? {
+ tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
getSourceFiles: function () { return host.getSourceFiles(); },
getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); })
@@ -33864,11 +33929,7 @@ var ts;
return symbolToTypeNode(typeAlias, context, 67897832 /* Type */);
}
else {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
}
else {
@@ -33882,11 +33943,7 @@ var ts;
}
var depth = context.symbolDepth.get(id) || 0;
if (depth > 10) {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
context.symbolDepth.set(id, depth + 1);
context.visitedTypes.set(typeId, true);
@@ -34071,10 +34128,15 @@ var ts;
typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context));
}
if (resolvedType.stringIndexInfo) {
- var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ?
- createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) :
- resolvedType.stringIndexInfo;
- typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context));
+ var indexSignature = void 0;
+ if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
+ indexSignature.type = createElidedInformationPlaceholder(context);
+ }
+ else {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
+ }
+ typeElements.push(indexSignature);
}
if (resolvedType.numberIndexInfo) {
typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
@@ -34105,8 +34167,16 @@ var ts;
return typeElements.length ? typeElements : undefined;
}
}
+ function createElidedInformationPlaceholder(context) {
+ context.approximateLength += 3;
+ if (!(context.flags & 1 /* NoTruncation */)) {
+ return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
+ }
+ return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
function addPropertyToElementList(propertySymbol, context, typeElements) {
- var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ?
+ var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */);
+ var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
anyType : getTypeOfSymbol(propertySymbol);
var saveEnclosingDeclaration = context.enclosingDeclaration;
context.enclosingDeclaration = undefined;
@@ -34136,8 +34206,14 @@ var ts;
}
else {
var savedFlags = context.flags;
- context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0;
- var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
+ var propertyTypeNode = void 0;
+ if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
+ propertyTypeNode = createElidedInformationPlaceholder(context);
+ }
+ else {
+ propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
context.flags = savedFlags;
var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined;
if (modifiers) {
@@ -34323,7 +34399,7 @@ var ts;
// Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
var chain;
var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
- if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) {
+ if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
ts.Debug.assert(chain && chain.length > 0);
}
@@ -34334,13 +34410,22 @@ var ts;
/** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
function getSymbolChain(symbol, meaning, endOfChain) {
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
+ var parentSpecifiers;
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
// Go up and add our parent.
- var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
- if (ts.length(parents)) {
- for (var _i = 0, _a = parents; _i < _a.length; _i++) {
- var parent = _a[_i];
+ var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
+ if (ts.length(parents_1)) {
+ parentSpecifiers = parents_1.map(function (symbol) {
+ return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
+ ? getSpecifierForModuleSymbol(symbol, context)
+ : undefined;
+ });
+ var indices = parents_1.map(function (_, i) { return i; });
+ indices.sort(sortByBestName);
+ var sortedParents = indices.map(function (i) { return parents_1[i]; });
+ for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
+ var parent = sortedParents_1[_i];
var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
if (parentChain) {
accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
@@ -34363,6 +34448,24 @@ var ts;
}
return [symbol];
}
+ function sortByBestName(a, b) {
+ var specifierA = parentSpecifiers[a];
+ var specifierB = parentSpecifiers[b];
+ if (specifierA && specifierB) {
+ var isBRelative = ts.pathIsRelative(specifierB);
+ if (ts.pathIsRelative(specifierA) === isBRelative) {
+ // Both relative or both non-relative, sort by number of parts
+ return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
+ }
+ if (isBRelative) {
+ // A is non-relative, B is relative: prefer A
+ return -1;
+ }
+ // A is relative, B is non-relative: prefer B
+ return 1;
+ }
+ return 0;
+ }
}
}
function typeParametersToTypeParameterDeclarations(symbol, context) {
@@ -34451,6 +34554,14 @@ var ts;
var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
var specifier = getSpecifierForModuleSymbol(chain[0], context);
+ if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
+ // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
+ // since declaration files with these kinds of references are liable to fail when published :(
+ context.encounteredError = true;
+ if (context.tracker.reportLikelyUnsafeImportRequiredError) {
+ context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
+ }
+ }
var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
@@ -34587,7 +34698,7 @@ var ts;
if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
function typePredicateToStringWorker(writer) {
- var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
+ var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
var printer = ts.createPrinter({ removeComments: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
@@ -36012,7 +36123,7 @@ var ts;
return type.resolvedBaseTypes = ts.emptyArray;
}
if (!isValidBaseType(baseType)) {
- error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType));
+ error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType));
return type.resolvedBaseTypes = ts.emptyArray;
}
if (type === baseType || hasBaseType(baseType, type)) {
@@ -36068,7 +36179,7 @@ var ts;
}
}
else {
- error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface);
+ error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -39368,7 +39479,7 @@ var ts;
if (accessExpression) {
markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */);
if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) {
- error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop));
+ error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
return missingType;
}
if (cacheSymbol) {
@@ -41632,7 +41743,8 @@ var ts;
var bestMatchingType = findMatchingDiscriminantType(source, target) ||
findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
findBestTypeForObjectLiteral(source, target) ||
- findBestTypeForInvokable(source, target);
+ findBestTypeForInvokable(source, target) ||
+ findMostOverlappyType(source, target);
isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
}
return 0 /* False */;
@@ -41667,6 +41779,34 @@ var ts;
return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
}
}
+ function findMostOverlappyType(source, unionTarget) {
+ var bestMatch;
+ var matchingCount = 0;
+ for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
+ var target_1 = _a[_i];
+ var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]);
+ if (overlap.flags & 4194304 /* Index */) {
+ // perfect overlap of keys
+ bestMatch = target_1;
+ matchingCount = Infinity;
+ }
+ else if (overlap.flags & 1048576 /* Union */) {
+ // Some subset overlap if we have only string literals.
+ // If we have a union of index types, it seems likely that we
+ // needed to elaborate between two generic mapped types anyway.
+ var len = ts.length(overlap.types);
+ if (len >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = len;
+ }
+ }
+ else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = 1;
+ }
+ }
+ return bestMatch;
+ }
// Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
function findMatchingDiscriminantType(source, target) {
if (target.flags & 1048576 /* Union */) {
@@ -42769,12 +42909,8 @@ var ts;
return true;
}
// A source signature partially matches a target signature if the target signature has no fewer required
- // parameters and no more overall parameters than the source signature (where a signature with a rest
- // parameter is always considered to have more overall parameters than one without).
- var sourceRestCount = sourceHasRestParameter ? 1 : 0;
- var targetRestCount = targetHasRestParameter ? 1 : 0;
- if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount ||
- sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) {
+ // parameters
+ if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
return true;
}
return false;
@@ -42880,6 +43016,9 @@ var ts;
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
}
+ function getElementTypeOfArrayType(type) {
+ return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined;
+ }
function isArrayLikeType(type) {
// A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
// or if it is not the undefined or null type and if it is assignable to ReadonlyArray
@@ -43252,6 +43391,16 @@ var ts;
diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
break;
case 151 /* Parameter */:
+ var param = declaration;
+ if (ts.isIdentifier(param.name) &&
+ (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
+ param.parent.parameters.indexOf(param) > -1 &&
+ (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
+ param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
+ var newName = "arg" + param.parent.parameters.indexOf(param);
+ errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
+ return;
+ }
diagnostic = declaration.dotDotDotToken ?
noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage :
noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
@@ -45653,7 +45802,12 @@ var ts;
return errorType;
}
if (isReadonlySymbol(localOrExportSymbol)) {
- error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol));
+ if (localOrExportSymbol.flags & 3 /* Variable */) {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
+ }
+ else {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
+ }
return errorType;
}
}
@@ -47138,6 +47292,17 @@ var ts;
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
return createIndexInfo(unionType, /*isReadonly*/ false);
}
+ function getImmediateAliasedSymbol(symbol) {
+ ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
+ var links = getSymbolLinks(symbol);
+ if (!links.immediateTarget) {
+ var node = getDeclarationOfAliasSymbol(symbol);
+ if (!node)
+ return ts.Debug.fail();
+ links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
+ }
+ return links.immediateTarget;
+ }
function checkObjectLiteral(node, checkMode) {
var inDestructuringPattern = ts.isAssignmentTarget(node);
// Grammar checking
@@ -47605,16 +47770,31 @@ var ts;
function getJsxElementChildrenPropertyName(jsxNamespace) {
return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
- function getUninstantiatedJsxSignaturesOfType(elementType) {
+ function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
+ if (elementType.flags & 4 /* String */) {
+ return [anySignature];
+ }
+ else if (elementType.flags & 128 /* StringLiteral */) {
+ var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
+ if (!intrinsicType) {
+ error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
+ return ts.emptyArray;
+ }
+ else {
+ var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
+ return [fakeSignature];
+ }
+ }
+ var apparentElemType = getApparentType(elementType);
// Resolve the signatures, preferring constructor
- var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
+ var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
if (signatures.length === 0) {
// No construct signatures, try call signatures
- signatures = getSignaturesOfType(elementType, 0 /* Call */);
+ signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
}
- if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) {
+ if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
// If each member has some combination of new/call signatures; make a union signature list for those
- signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType));
+ signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
}
return signatures;
}
@@ -47987,7 +48167,7 @@ var ts;
checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop);
if (assignmentKind) {
if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) {
- error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right));
+ error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
return errorType;
}
}
@@ -49555,20 +49735,8 @@ var ts;
if (apparentType === errorType) {
return resolveErrorCall(node);
}
- if (exprTypes.flags & 128 /* StringLiteral */) {
- var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node);
- if (!intrinsicType) {
- error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements);
- return resolveUntypedCall(node);
- }
- else {
- var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes);
- return fakeSignature;
- }
- }
- var signatures = getUninstantiatedJsxSignaturesOfType(apparentType);
- if (exprTypes.flags & 4 /* String */ || isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
+ var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
+ if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
return resolveUntypedCall(node);
}
if (signatures.length === 0) {
@@ -51193,8 +51361,17 @@ var ts;
leftType;
case 59 /* EqualsToken */:
var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
- checkAssignmentDeclaration(declKind, right);
+ checkAssignmentDeclaration(declKind, rightType);
if (isAssignmentDeclaration(declKind)) {
+ if (!(rightType.flags & 524288 /* Object */) ||
+ declKind !== 2 /* ModuleExports */ &&
+ declKind !== 6 /* Prototype */ &&
+ !isEmptyObjectType(rightType) &&
+ !isFunctionObjectType(rightType) &&
+ !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
+ // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
+ checkAssignmentOperator(rightType);
+ }
return leftType;
}
else {
@@ -51209,10 +51386,9 @@ var ts;
default:
return ts.Debug.fail();
}
- function checkAssignmentDeclaration(kind, right) {
+ function checkAssignmentDeclaration(kind, rightType) {
if (kind === 2 /* ModuleExports */) {
- var rightType_1 = checkExpression(right, checkMode);
- for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
var prop = _a[_i];
var propType = getTypeOfSymbol(prop);
if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
@@ -53277,7 +53453,7 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
- if (produceDiagnostics) {
+ if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
@@ -53298,9 +53474,6 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 241 /* InterfaceDeclaration */:
- checkUnusedTypeParameters(node, addDiagnostic);
- break;
case 279 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
@@ -53317,7 +53490,7 @@ var ts;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- if (node.body) {
+ if (node.body) { // Don't report unused parameters in overloads
checkUnusedLocalsAndParameters(node, addDiagnostic);
}
checkUnusedTypeParameters(node, addDiagnostic);
@@ -53328,9 +53501,12 @@ var ts;
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 242 /* TypeAliasDeclaration */:
- case 176 /* InferType */:
+ case 241 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 176 /* InferType */:
+ checkUnusedInferTypeParameter(node, addDiagnostic);
+ break;
default:
ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
}
@@ -53345,77 +53521,73 @@ var ts;
return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
}
function checkUnusedClassMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
- var member = _a[_i];
- switch (member.kind) {
- case 156 /* MethodDeclaration */:
- case 154 /* PropertyDeclaration */:
- case 158 /* GetAccessor */:
- case 159 /* SetAccessor */:
- if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
- // Already would have reported an error on the getter.
- break;
- }
- var symbol = getSymbolOfNode(member);
- if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
- addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
- }
+ for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ switch (member.kind) {
+ case 156 /* MethodDeclaration */:
+ case 154 /* PropertyDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
+ // Already would have reported an error on the getter.
break;
- case 157 /* Constructor */:
- for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
- var parameter = _c[_b];
- if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
- addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
- }
+ }
+ var symbol = getSymbolOfNode(member);
+ if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
+ addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
+ }
+ break;
+ case 157 /* Constructor */:
+ for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
+ var parameter = _c[_b];
+ if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
+ addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
}
- break;
- case 162 /* IndexSignature */:
- case 217 /* SemicolonClassElement */:
- // Can't be private
- break;
- default:
- ts.Debug.fail();
- }
+ }
+ break;
+ case 162 /* IndexSignature */:
+ case 217 /* SemicolonClassElement */:
+ // Can't be private
+ break;
+ default:
+ ts.Debug.fail();
}
}
}
+ function checkUnusedInferTypeParameter(node, addDiagnostic) {
+ var typeParameter = node.typeParameter;
+ if (isTypeParameterUnused(typeParameter)) {
+ addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ }
+ }
function checkUnusedTypeParameters(node, addDiagnostic) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
- if (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node)
+ if (ts.last(getSymbolOfNode(node).declarations) !== node)
return;
- if (node.kind === 176 /* InferType */) {
- var typeParameter = node.typeParameter;
- if (isTypeParameterUnused(typeParameter)) {
- addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
+ var seenParentsWithEveryUnused = new ts.NodeSet();
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var typeParameter = typeParameters_2[_i];
+ if (!isTypeParameterUnused(typeParameter))
+ continue;
+ var name = ts.idText(typeParameter.name);
+ var parent = typeParameter.parent;
+ if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
+ if (seenParentsWithEveryUnused.tryAdd(parent)) {
+ var range = ts.isJSDocTemplateTag(parent)
+ // Whole @template tag
+ ? ts.rangeOfNode(parent)
+ // Include the `<>` in the error message
+ : ts.rangeOfTypeParameters(parent.typeParameters);
+ var only = typeParameters.length === 1;
+ var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
+ var arg0 = only ? name : undefined;
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
+ }
}
- }
- else {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
- if (!isTypeParameterUnused(typeParameter))
- continue;
- var name = ts.idText(typeParameter.name);
- var parent = typeParameter.parent;
- if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
- if (seenParentsWithEveryUnused.tryAdd(parent)) {
- var range = ts.isJSDocTemplateTag(parent)
- // Whole @template tag
- ? ts.rangeOfNode(parent)
- // Include the `<>` in the error message
- : ts.rangeOfTypeParameters(parent.typeParameters);
- var only = typeParameters.length === 1;
- var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
- var arg0 = only ? name : undefined;
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
- }
- }
- else {
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
- }
+ else {
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
}
}
}
@@ -53836,9 +54008,9 @@ var ts;
var nameText = ts.getTextOfPropertyName(name);
if (nameText) {
var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217
- markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
- if (parent.initializer && property) {
- checkPropertyAccessibility(parent, parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
+ if (property) {
+ markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
+ checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
}
}
}
@@ -54896,7 +55068,7 @@ var ts;
}
}
else {
- error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface);
+ error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -56502,7 +56674,10 @@ var ts;
}
if (isDeclarationNameOrImportPropertyName(node)) {
// This is a declaration, call getSymbolOfNode
- return getSymbolOfNode(parent);
+ var parentSymbol = getSymbolOfNode(parent);
+ return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
+ ? getImmediateAliasedSymbol(parentSymbol)
+ : parentSymbol;
}
else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
return getSymbolOfNode(parent.parent);
@@ -64710,7 +64885,7 @@ var ts;
};
function processMapping(mapping) {
var generatedPosition = generatedFile !== undefined
- ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
: -1;
var source;
var sourcePosition;
@@ -64719,7 +64894,7 @@ var ts;
var sourceFile = host.getSourceFileLike(sourceFilePath);
source = map.sources[mapping.sourceIndex];
sourcePosition = sourceFile !== undefined
- ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
: -1;
}
return {
@@ -79709,6 +79884,7 @@ var ts;
reportInaccessibleThisError: reportInaccessibleThisError,
reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
+ reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
moduleResolverHost: host,
trackReferencedAmbientModule: trackReferencedAmbientModule,
trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode
@@ -79797,6 +79973,11 @@ var ts;
context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
}
}
+ function reportLikelyUnsafeImportRequiredError(specifier) {
+ if (errorNameNode) {
+ context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
+ }
+ }
function transformRoot(node) {
if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
@@ -82784,7 +82965,7 @@ var ts;
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
function emitClassExpression(node) {
@@ -83522,7 +83703,7 @@ var ts;
}
function emitSpreadAssignment(node) {
if (node.expression) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
}
@@ -85492,7 +85673,7 @@ var ts;
var text;
try {
ts.performance.mark("beforeIORead");
- text = system.readFile(fileName, options.charset);
+ text = compilerHost.readFile(fileName);
ts.performance.mark("afterIORead");
ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
@@ -85518,7 +85699,12 @@ var ts;
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
- system.createDirectory(directoryPath);
+ if (compilerHost.createDirectory) {
+ compilerHost.createDirectory(directoryPath);
+ }
+ else {
+ system.createDirectory(directoryPath);
+ }
}
}
var outputFingerprints;
@@ -85570,7 +85756,7 @@ var ts;
}
var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
var realpath = system.realpath && (function (path) { return system.realpath(path); });
- return {
+ var compilerHost = {
getSourceFile: getSourceFile,
getDefaultLibLocation: getDefaultLibLocation,
getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
@@ -85586,10 +85772,113 @@ var ts;
getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return system.getDirectories(path); },
realpath: realpath,
- readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }
+ readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
+ createDirectory: function (d) { return system.createDirectory(d); }
};
+ return compilerHost;
}
ts.createCompilerHostWorker = createCompilerHostWorker;
+ /*@internal*/
+ function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) {
+ var originalReadFile = host.readFile;
+ var originalFileExists = host.fileExists;
+ var originalDirectoryExists = host.directoryExists;
+ var originalCreateDirectory = host.createDirectory;
+ var originalWriteFile = host.writeFile;
+ var originalGetSourceFile = host.getSourceFile;
+ var readFileCache = ts.createMap();
+ var fileExistsCache = ts.createMap();
+ var directoryExistsCache = ts.createMap();
+ var sourceFileCache = ts.createMap();
+ var readFileWithCache = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value || undefined;
+ return setReadFileCache(key, fileName);
+ };
+ var setReadFileCache = function (key, fileName) {
+ var newValue = originalReadFile.call(host, fileName);
+ readFileCache.set(key, newValue || false);
+ return newValue;
+ };
+ host.readFile = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value; // could be .d.ts from output
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return originalReadFile.call(host, fileName);
+ }
+ return setReadFileCache(key, fileName);
+ };
+ if (useCacheForSourceFile) {
+ host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
+ var key = toPath(fileName);
+ var value = sourceFileCache.get(key);
+ if (value)
+ return value;
+ var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile);
+ if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
+ sourceFileCache.set(key, sourceFile);
+ }
+ return sourceFile;
+ };
+ }
+ // fileExists for any kind of extension
+ host.fileExists = function (fileName) {
+ var key = toPath(fileName);
+ var value = fileExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalFileExists.call(host, fileName);
+ fileExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
+ var key = toPath(fileName);
+ fileExistsCache.delete(key);
+ var value = readFileCache.get(key);
+ if (value && value !== data) {
+ readFileCache.delete(key);
+ sourceFileCache.delete(key);
+ }
+ else if (useCacheForSourceFile) {
+ var sourceFile = sourceFileCache.get(key);
+ if (sourceFile && sourceFile.text !== data) {
+ sourceFileCache.delete(key);
+ }
+ }
+ originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
+ };
+ // directoryExists
+ if (originalDirectoryExists && originalCreateDirectory) {
+ host.directoryExists = function (directory) {
+ var key = toPath(directory);
+ var value = directoryExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalDirectoryExists.call(host, directory);
+ directoryExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.createDirectory = function (directory) {
+ var key = toPath(directory);
+ directoryExistsCache.delete(key);
+ originalCreateDirectory.call(host, directory);
+ };
+ }
+ return {
+ originalReadFile: originalReadFile,
+ originalFileExists: originalFileExists,
+ originalDirectoryExists: originalDirectoryExists,
+ originalCreateDirectory: originalCreateDirectory,
+ originalWriteFile: originalWriteFile,
+ originalGetSourceFile: originalGetSourceFile,
+ readFileWithCache: readFileWithCache
+ };
+ }
+ ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache;
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (ts.getEmitDeclarations(program.getCompilerOptions())) {
@@ -85976,6 +86265,7 @@ var ts;
// A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
var resolvedProjectReferences;
var projectReferenceRedirects;
+ var mapFromFileToProjectReferenceRedirects;
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2 /* Completely */) {
@@ -87334,15 +87624,20 @@ var ts;
* Get the referenced project if the file is input file from that reference project
*/
function getResolvedProjectReferenceToRedirect(fileName) {
- return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
- // not input file from the referenced project, ignore
- if (!referencedProject ||
- toPath(options.configFilePath) === referenceProjectPath ||
- !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) {
- return undefined;
- }
- return referencedProject;
- });
+ if (mapFromFileToProjectReferenceRedirects === undefined) {
+ mapFromFileToProjectReferenceRedirects = ts.createMap();
+ forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
+ // not input file from the referenced project, ignore
+ if (referencedProject &&
+ toPath(options.configFilePath) !== referenceProjectPath) {
+ referencedProject.commandLine.fileNames.forEach(function (f) {
+ return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
+ });
+ }
+ });
+ }
+ var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
+ return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
}
function forEachResolvedProjectReference(cb) {
return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
@@ -89705,6 +90000,7 @@ var ts;
}
return count;
}
+ moduleSpecifiers.countPathComponents = countPathComponents;
function usesJsExtensionOnImports(_a) {
var imports = _a.imports;
return ts.firstDefined(imports, function (_a) {
@@ -90912,6 +91208,7 @@ var ts;
var missingRoots = ts.createMap();
var globalDependencyGraph;
var writeFileName = function (s) { return host.trace && host.trace(s); };
+ var readFileWithCache = function (f) { return host.readFile(f); };
// Watch state
var diagnostics = createFileMap(toPath);
var projectPendingBuild = createFileMap(toPath);
@@ -91447,19 +91744,15 @@ var ts;
options: configFile.options,
configFileParsingDiagnostics: configFile.errors
};
+ if (host.beforeCreateProgram) {
+ host.beforeCreateProgram(options);
+ }
var program = ts.createProgram(programOptions);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
}
- // Don't emit .d.ts if there are decl file errors
- if (ts.getEmitDeclarations(program.getCompilerOptions())) {
- var declDiagnostics = program.getDeclarationDiagnostics();
- if (declDiagnostics.length) {
- return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
- }
- }
// Same as above but now for semantic diagnostics
var semanticDiagnostics = program.getSemanticDiagnostics();
if (semanticDiagnostics.length) {
@@ -91467,27 +91760,37 @@ var ts;
}
var newestDeclarationFileContentChangedTime = minimumDate;
var anyDtsChanged = false;
- var emitDiagnostics;
- var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); };
- ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) {
+ var declDiagnostics;
+ var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
+ var outputFiles = [];
+ ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); });
+ // Don't emit .d.ts if there are decl file errors
+ if (declDiagnostics) {
+ return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
+ }
+ // Actual Emit
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
var priorChangeTime;
- if (!anyDtsChanged && isDeclarationFile(fileName)) {
+ if (!anyDtsChanged && isDeclarationFile(name)) {
// Check for unchanged .d.ts files
- if (host.fileExists(fileName) && host.readFile(fileName) === content) {
- priorChangeTime = host.getModifiedTime(fileName);
+ if (host.fileExists(name) && readFileWithCache(name) === text) {
+ priorChangeTime = host.getModifiedTime(name);
}
else {
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
anyDtsChanged = true;
}
}
- host.writeFile(fileName, content, writeBom, onError, ts.emptyArray);
+ ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark);
if (priorChangeTime !== undefined) {
newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
- unchangedOutputs.setValue(fileName, priorChangeTime);
+ unchangedOutputs.setValue(name, priorChangeTime);
}
});
- if (emitDiagnostics) {
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
}
var status = {
@@ -91496,11 +91799,17 @@ var ts;
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
}
}
@@ -91567,11 +91876,16 @@ var ts;
if (options.watch) {
reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode);
}
+ // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api
+ // Override readFile for json files and output .d.ts to cache the text
+ var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache;
+ var savedReadFileWithCache = readFileWithCache;
+ readFileWithCache = newReadFileWithCache;
var graph = getGlobalDependencyGraph();
reportBuildQueue(graph);
var anyFailed = false;
- for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
- var next = _a[_i];
+ for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) {
+ var next = _b[_i];
var proj = parseConfigFile(next);
if (proj === undefined) {
reportParseConfigFileDiagnostic(next);
@@ -91613,6 +91927,13 @@ var ts;
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
+ host.readFile = originalReadFile;
+ host.fileExists = originalFileExists;
+ host.directoryExists = originalDirectoryExists;
+ host.createDirectory = originalCreateDirectory;
+ host.writeFile = originalWriteFile;
+ readFileWithCache = savedReadFileWithCache;
+ host.getSourceFile = originalGetSourceFile;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
function reportParseConfigFileDiagnostic(proj) {
@@ -92209,12 +92530,6 @@ var ts;
})(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {}));
/* @internal */
ts.emptyOptions = {};
- var TextChange = /** @class */ (function () {
- function TextChange() {
- }
- return TextChange;
- }());
- ts.TextChange = TextChange;
var HighlightSpanKind;
(function (HighlightSpanKind) {
HighlightSpanKind["none"] = "none";
@@ -92678,6 +92993,10 @@ var ts;
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
ts.isLabelName = isLabelName;
+ function isTagName(node) {
+ return ts.isJSDocTag(node.parent) && node.parent.tagName === node;
+ }
+ ts.isTagName = isTagName;
function isRightSideOfQualifiedName(node) {
return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node;
}
@@ -93568,6 +93887,7 @@ var ts;
ts.createTextChange = createTextChange;
ts.typeKeywords = [
120 /* AnyKeyword */,
+ 146 /* BigIntKeyword */,
123 /* BooleanKeyword */,
87 /* FalseKeyword */,
129 /* KeyOfKeyword */,
@@ -94001,9 +94321,7 @@ var ts;
}
ts.signatureToDisplayParts = signatureToDisplayParts;
function isImportOrExportSpecifierName(location) {
- return !!location.parent &&
- (location.parent.kind === 253 /* ImportSpecifier */ || location.parent.kind === 257 /* ExportSpecifier */) &&
- location.parent.propertyName === location;
+ return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location;
}
ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
/**
@@ -95425,26 +95743,21 @@ var ts;
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
*/
- function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) {
+ function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) {
// Make all paths absolute/normalized if they are not already
rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); });
// Determine the path to the directory containing the script relative to the root directory it is contained within
var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) {
- return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined;
+ return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined;
}); // TODO: GH#18217
// Now find a path for each potential directory that is to be merged with the one containing the script
- return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
}
- function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensionOptions, compilerOptions, host, exclude) {
+ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) {
var basePath = compilerOptions.project || host.getCurrentDirectory();
var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
- var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase);
- var result = [];
- for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) {
- var baseDirectory = baseDirectories_1[_i];
- getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude, result);
- }
- return result;
+ var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
+ return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); });
}
/**
* Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
@@ -96675,7 +96988,8 @@ var ts;
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
isInSnippetScope = isSnippetScope(scopeNode);
- var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
+ var isTypeOnly = isTypeOnlyCompletion();
+ var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) {
@@ -96724,9 +97038,9 @@ var ts;
}
}
function filterGlobalCompletion(symbols) {
- var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
- var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
- if (isTypeOnlyCompletion)
+ var isTypeOnly = isTypeOnlyCompletion();
+ var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
+ if (isTypeOnly)
keywordFilters = 6 /* TypeKeywords */;
ts.filterMutate(symbols, function (symbol) {
if (!ts.isSourceFile(location)) {
@@ -96742,7 +97056,7 @@ var ts;
if (allowTypes) {
// Its a type, but you can reach it by namespace.type as well
var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol);
- if (symbolAllowedAsType || isTypeOnlyCompletion) {
+ if (symbolAllowedAsType || isTypeOnly) {
return symbolAllowedAsType;
}
}
@@ -96751,6 +97065,9 @@ var ts;
return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */);
});
}
+ function isTypeOnlyCompletion() {
+ return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
+ }
function isContextTokenValueLocation(contextToken) {
return contextToken &&
contextToken.kind === 104 /* TypeOfKeyword */ &&
@@ -97136,6 +97453,7 @@ var ts;
if (contextToken) {
var parent = contextToken.parent;
switch (contextToken.kind) {
+ case 30 /* GreaterThanToken */: // End of a type argument list
case 29 /* LessThanSlashToken */:
case 42 /* SlashToken */:
case 72 /* Identifier */:
@@ -97144,6 +97462,11 @@ var ts;
case 267 /* JsxAttribute */:
case 269 /* JsxSpreadAttribute */:
if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) {
+ if (contextToken.kind === 30 /* GreaterThanToken */) {
+ var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined);
+ if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */))
+ break;
+ }
return parent;
}
else if (parent.kind === 267 /* JsxAttribute */) {
@@ -98562,7 +98885,7 @@ var ts;
return undefined;
}
var lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
- return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false };
+ return { kind: 0 /* Import */, symbol: lhsSymbol };
}
else {
return exportInfo(symbol, getExportKindForDeclaration(exportNode));
@@ -98632,7 +98955,7 @@ var ts;
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
- return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
+ return { kind: 0 /* Import */, symbol: importedSymbol };
}
}
function exportInfo(symbol, kind) {
@@ -98677,18 +99000,16 @@ var ts;
var parent = node.parent;
switch (parent.kind) {
case 248 /* ImportEqualsDeclaration */:
- return parent.name === node && isExternalModuleImportEquals(parent)
- ? { isNamedImport: false }
- : undefined;
+ return parent.name === node && isExternalModuleImportEquals(parent);
case 253 /* ImportSpecifier */:
// For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
- return parent.propertyName ? undefined : { isNamedImport: true };
+ return !parent.propertyName;
case 250 /* ImportClause */:
case 251 /* NamespaceImport */:
ts.Debug.assert(parent.name === node);
- return { isNamedImport: false };
+ return true;
default:
- return undefined;
+ return false;
}
}
function getExportInfo(exportSymbol, exportKind, checker) {
@@ -98806,7 +99127,7 @@ var ts;
}
}
function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) {
- return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); });
+ return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); });
}
FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries;
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
@@ -98860,8 +99181,8 @@ var ts;
var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
return { displayParts: displayParts, kind: symbolKind };
}
- function toRenameLocation(entry, originalNode) {
- return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode));
+ function toRenameLocation(entry, originalNode, checker) {
+ return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker));
}
FindAllReferences.toRenameLocation = toRenameLocation;
function toReferenceEntry(entry) {
@@ -98890,25 +99211,27 @@ var ts;
return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName };
}
}
- function getPrefixAndSuffixText(entry, originalNode) {
+ function getPrefixAndSuffixText(entry, originalNode, checker) {
if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) {
var node = entry.node, kind = entry.kind;
var name = originalNode.text;
var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent);
if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) {
- if (kind === 3 /* SearchedLocalFoundProperty */) {
- return { prefixText: name + ": " };
- }
- else if (kind === 4 /* SearchedPropertyFoundLocal */) {
- return { suffixText: ": " + name };
- }
- else {
- return isShorthandAssignment
+ var prefixColon = { prefixText: name + ": " };
+ var suffixColon = { suffixText: ": " + name };
+ return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon
+ : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon
// In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol.
- ? { suffixText: ": " + name }
// For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol.
- : { prefixText: name + ": " };
- }
+ : isShorthandAssignment ? suffixColon : prefixColon;
+ }
+ else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
+ // If the original symbol was using this alias, just rename the alias.
+ var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
+ return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions;
+ }
+ else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
+ return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name };
}
}
return ts.emptyOptions;
@@ -99163,13 +99486,18 @@ var ts;
return undefined;
}
/** Core find-all-references algorithm for a normal symbol. */
- function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
- symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
+ function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
+ var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol;
// Compute the meaning from the location and the symbol it references
var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
var result = [];
var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
- if (node && node.kind === 80 /* DefaultKeyword */) {
+ var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier);
+ if (exportSpecifier) {
+ // When renaming at an export specifier, rename the export and not the thing being exported.
+ getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true);
+ }
+ else if (node && node.kind === 80 /* DefaultKeyword */) {
addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
@@ -99207,15 +99535,11 @@ var ts;
}
}
/** Handle a few special cases relating to export/import specifiers. */
- function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) {
+ function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) {
var parent = node.parent;
- if (ts.isExportSpecifier(parent)) {
+ if (ts.isExportSpecifier(parent) && !isForRename) {
return getLocalSymbolForExportSpecifier(node, symbol, parent, checker);
}
- if (ts.isImportSpecifier(parent) && parent.propertyName === node) {
- // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import.
- return checker.getImmediateAliasedSymbol(symbol);
- }
// If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references.
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
@@ -99378,7 +99702,8 @@ var ts;
var indirectUser = indirectUsers_2[_b];
for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) {
var node = _d[_c];
- if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) {
+ // Import specifiers should be handled by importSearches
+ if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) {
cb(node);
}
}
@@ -99394,7 +99719,7 @@ var ts;
if (!ts.isIdentifier(singleRef))
return false;
// At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */);
+ return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */);
}
// Go to the symbol we imported from and find references for it.
function searchForImportedSymbol(symbol, state) {
@@ -99673,16 +99998,16 @@ var ts;
}
getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
}
- function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) {
+ function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) {
var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
var exportDeclaration = parent.parent;
var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
- if (!search.includes(localSymbol)) {
+ if (!alwaysGetReferences && !search.includes(localSymbol)) {
return;
}
if (!propertyName) {
// Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export)
- if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) {
+ if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) {
addRef();
}
}
@@ -99693,7 +100018,7 @@ var ts;
addRef();
}
if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) {
- addReference(name, referenceSymbol, state);
+ addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state);
}
}
else {
@@ -99702,15 +100027,14 @@ var ts;
}
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
- if (!(referenceLocation === propertyName && state.options.isForRename)) {
+ if (!state.options.isForRename || alwaysGetReferences) {
var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
- var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker);
- if (!exportInfo)
- return ts.Debug.fail();
- searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state);
+ var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
+ var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker));
+ searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
}
// At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
- if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) {
+ if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) {
var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
if (imported)
searchForImportedSymbol(imported, state);
@@ -99742,12 +100066,11 @@ var ts;
return;
var symbol = importOrExport.symbol;
if (importOrExport.kind === 0 /* Import */) {
- if (!state.options.isForRename || importOrExport.isNamedImport) {
+ if (!state.options.isForRename) {
searchForImportedSymbol(symbol, state);
}
}
else {
- // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching.
searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
}
}
@@ -103745,7 +104068,7 @@ var ts;
function getEnclosingDeclarationFromInvocation(invocation) {
return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
}
- var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
+ var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) {
var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
@@ -104911,16 +105234,11 @@ var ts;
this.options = options;
}
FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
- ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null");
- ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null");
- ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null");
- ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null");
- ts.Debug.assert(commonParent !== undefined, "commonParent is null");
- this.currentTokenSpan = currentRange;
- this.currentTokenParent = currentTokenParent;
- this.nextTokenSpan = nextRange;
- this.nextTokenParent = nextTokenParent;
- this.contextNode = commonParent;
+ this.currentTokenSpan = ts.Debug.assertDefined(currentRange);
+ this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent);
+ this.nextTokenSpan = ts.Debug.assertDefined(nextRange);
+ this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent);
+ this.contextNode = ts.Debug.assertDefined(commonParent);
// drop cached results
this.contextNodeAllOnSameLine = undefined;
this.nextNodeAllOnSameLine = undefined;
@@ -107646,7 +107964,6 @@ var ts;
};
ChangeTracker.prototype.deleteRange = function (sourceFile, range) {
this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range });
- return this;
};
ChangeTracker.prototype.delete = function (sourceFile, node) {
this.deletedNodes.push({ sourceFile: sourceFile, node: node });
@@ -107659,7 +107976,6 @@ var ts;
var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
- return this;
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
if (options === void 0) { options = {}; }
@@ -107670,11 +107986,10 @@ var ts;
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
if (options === void 0) { options = {}; }
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
- return this;
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
+ this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
@@ -107683,18 +107998,17 @@ var ts;
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
if (options === void 0) { options = {}; }
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
- return this;
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
+ this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
+ this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
var next = ts.findNextToken(node, node.parent, sourceFile);
@@ -107702,7 +108016,7 @@ var ts;
};
ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
- return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
+ this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
};
ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
if (options === void 0) { options = {}; }
@@ -107951,11 +108265,11 @@ var ts;
if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
- return this;
+ return;
}
var index = ts.indexOfNode(containingList, after);
if (index < 0) {
- return this;
+ return;
}
var end = after.getEnd();
if (index !== containingList.length - 1) {
@@ -108053,7 +108367,6 @@ var ts;
this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
}
}
- return this;
};
ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () {
var _this = this;
@@ -109270,9 +109583,8 @@ var ts;
cancellationToken.throwIfCancellationRequested();
inferTypeFromContext(reference, checker, usageContext);
}
- var isConstructor = declaration.kind === 157 /* Constructor */;
- var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
- return callContexts && declaration.parameters.map(function (parameter, parameterIndex) {
+ var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []);
+ return declaration.parameters.map(function (parameter, parameterIndex) {
var types = [];
var isRest = ts.isRestParameter(parameter);
var isOptional = false;
@@ -109292,7 +109604,8 @@ var ts;
}
}
if (ts.isIdentifier(parameter.name)) {
- types.push.apply(types, inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken));
+ var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken);
+ types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred));
}
var type = unifyFromContext(types, checker);
return {
@@ -109364,8 +109677,7 @@ var ts;
usageContext.isNumber = true;
break;
case 38 /* PlusToken */:
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
break;
// case SyntaxKind.ExclamationToken:
// no inferences here;
@@ -109427,8 +109739,7 @@ var ts;
usageContext.isString = true;
}
else {
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
}
break;
// AssignmentOperators
@@ -109493,8 +109804,7 @@ var ts;
}
function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) {
if (node === parent.argumentExpression) {
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
return;
}
else {
@@ -109509,18 +109819,48 @@ var ts;
}
}
}
+ function removeLowPriorityInferences(inferences, priorities) {
+ var toRemove = [];
+ for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
+ var i = inferences_2[_i];
+ for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
+ var _b = priorities_1[_a], high = _b.high, low = _b.low;
+ if (high(i)) {
+ ts.Debug.assert(!low(i));
+ toRemove.push(low);
+ }
+ }
+ }
+ return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); });
+ }
function unifyFromContext(inferences, checker, fallback) {
if (fallback === void 0) { fallback = checker.getAnyType(); }
if (!inferences.length)
return fallback;
- var hasNonVacuousType = inferences.some(function (i) { return !(i.flags & (1 /* Any */ | 16384 /* Void */)); });
- var hasNonVacuousNonAnonymousType = inferences.some(function (i) { return !(i.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(i) & 16 /* Anonymous */); });
- var anons = inferences.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; });
- var good = [];
- if (!hasNonVacuousNonAnonymousType && anons.length) {
+ // 1. string or number individually override string | number
+ // 2. non-any, non-void overrides any or void
+ // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types
+ var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]);
+ var priorities = [
+ {
+ high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); },
+ low: function (t) { return t === stringNumber; }
+ },
+ {
+ high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); },
+ low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); }
+ },
+ {
+ high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); },
+ low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); }
+ }
+ ];
+ var good = removeLowPriorityInferences(inferences, priorities);
+ var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; });
+ if (anons.length) {
+ good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); });
good.push(unifyAnonymousTypes(anons, checker));
}
- good.push.apply(good, inferences.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */) && !(hasNonVacuousType && i.flags & (1 /* Any */ | 16384 /* Void */)); }));
return checker.getWidenedType(checker.getUnionType(good));
}
InferFromReference.unifyFromContext = unifyFromContext;
@@ -109568,6 +109908,9 @@ var ts;
if (usageContext.isString) {
types.push(checker.getStringType());
}
+ if (usageContext.isNumberOrString) {
+ types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
+ }
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
@@ -109578,7 +109921,7 @@ var ts;
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
}
if (usageContext.numberIndexContext) {
- return [checker.createArrayType(recur(usageContext.numberIndexContext))];
+ types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
var members_6 = ts.createUnderscoreEscapedMap();
@@ -115320,7 +115663,7 @@ var ts;
// readonly modifier only existed in classLikeDeclaration
var constructor = ts.getFirstConstructorWithBody(container);
if (constructor) {
- updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
}
}
else {
@@ -115373,7 +115716,7 @@ var ts;
isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent,
- originalName: declaration.name,
+ originalName: declaration.name.text,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
@@ -115424,22 +115767,23 @@ var ts;
? changeTracker.insertNodeAfterComma(file, declaration, accessor)
: changeTracker.insertNodeAfter(file, declaration, accessor);
}
- function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) {
if (!constructor.body)
return;
- var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
- var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) {
- return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined;
- });
- ts.forEach(referenceEntries, function (entry) {
- var parent = entry.parent;
- var accessorName = ts.createIdentifier(fieldName.text);
- var node = ts.isBinaryExpression(parent)
- ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
- : ts.isPropertyAccessExpression(parent)
- ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
- : ts.Debug.fail("Unexpected write access token");
- changeTracker.replaceNode(file, parent, node);
+ constructor.body.forEachChild(function recur(node) {
+ if (ts.isElementAccessExpression(node) &&
+ node.expression.kind === 100 /* ThisKeyword */ &&
+ ts.isStringLiteral(node.argumentExpression) &&
+ node.argumentExpression.text === originalName &&
+ ts.isWriteAccess(node)) {
+ changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName));
+ }
+ if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) {
+ changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName));
+ }
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
+ node.forEachChild(recur);
+ }
});
}
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
@@ -117381,7 +117725,7 @@ var ts;
function shouldGetType(sourceFile, node, position) {
switch (node.kind) {
case 72 /* Identifier */:
- return !ts.isLabelName(node);
+ return !ts.isLabelName(node) && !ts.isTagName(node);
case 189 /* PropertyAccessExpression */:
case 148 /* QualifiedName */:
// Don't return quickInfo if inside the comment in `a/**/.b`
@@ -117963,7 +118307,7 @@ var ts;
function initializeNameTable(sourceFile) {
var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap();
sourceFile.forEachChild(function walk(node) {
- if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
+ if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
var text = ts.getEscapedTextOfIdentifierOrLiteral(node);
nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
}
@@ -118877,9 +119221,15 @@ var ts;
if ("directoryExists" in this.shimHost) {
this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
}
+ else {
+ this.directoryExists = undefined; // TODO: GH#18217
+ }
if ("realpath" in this.shimHost) {
this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217
}
+ else {
+ this.realpath = undefined; // TODO: GH#18217
+ }
}
CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) {
var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
@@ -119850,6 +120200,18 @@ var ts;
this.host = host;
this.fileName = fileName;
this.info = info;
+ /**
+ * True if the text is for the file thats open in the editor
+ */
+ this.isOpen = false;
+ /**
+ * True if the text present is the text from the file on the disk
+ */
+ this.ownFileText = false;
+ /**
+ * True when reloading contents of file from the disk is pending
+ */
+ this.pendingReloadFromDisk = false;
this.version = initialVersion || { svc: 0, text: 0 };
}
TextStorage.prototype.getVersion = function () {
@@ -119863,10 +120225,12 @@ var ts;
TextStorage.prototype.useScriptVersionCache_TestOnly = function () {
this.switchToScriptVersionCache();
};
+ /** Public for testing */
TextStorage.prototype.useText = function (newText) {
this.svc = undefined;
this.text = newText;
this.lineMap = undefined;
+ this.fileSize = undefined;
this.version.text++;
};
TextStorage.prototype.edit = function (start, end, newText) {
@@ -119874,6 +120238,7 @@ var ts;
this.ownFileText = false;
this.text = undefined;
this.lineMap = undefined;
+ this.fileSize = undefined;
};
/**
* Set the contents as newText
@@ -119894,13 +120259,16 @@ var ts;
this.ownFileText = false;
return true;
}
+ return false;
};
/**
* Reads the contents from tempFile(if supplied) or own file and sets it as contents
* returns true if text changed
*/
TextStorage.prototype.reloadWithFileText = function (tempFileName) {
- var reloaded = this.reload(this.getFileText(tempFileName));
+ var _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize;
+ var reloaded = this.reload(newText);
+ this.fileSize = fileSize; // NB: after reload since reload clears it
this.ownFileText = !tempFileName || tempFileName === this.fileName;
return reloaded;
};
@@ -119917,6 +120285,22 @@ var ts;
TextStorage.prototype.delayReloadFromFileIntoText = function () {
this.pendingReloadFromDisk = true;
};
+ /**
+ * For telemetry purposes, we would like to be able to report the size of the file.
+ * However, we do not want telemetry to require extra file I/O so we report a size
+ * that may be stale (e.g. may not reflect change made on disk since the last reload).
+ * NB: Will read from disk if the file contents have never been loaded because
+ * telemetry falsely indicating size 0 would be counter-productive.
+ */
+ TextStorage.prototype.getTelemetryFileSize = function () {
+ return !!this.fileSize
+ ? this.fileSize
+ : !!this.text // Check text before svc because its length is cheaper
+ ? this.text.length // Could be wrong if this.pendingReloadFromDisk
+ : !!this.svc
+ ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk
+ : this.getSnapshot().getLength(); // Should be strictly correct
+ };
TextStorage.prototype.getSnapshot = function () {
return this.useScriptVersionCacheIfValidOrOpen()
? this.svc.getSnapshot()
@@ -119955,7 +120339,7 @@ var ts;
}
return this.svc.positionToLineOffset(position);
};
- TextStorage.prototype.getFileText = function (tempFileName) {
+ TextStorage.prototype.getFileTextAndSize = function (tempFileName) {
var _this = this;
var text;
var fileName = tempFileName || this.fileName;
@@ -119968,10 +120352,10 @@ var ts;
var service = this.info.containingProjects[0].projectService;
service.logger.info("Skipped loading contents of large file " + fileName + " for info " + this.info.fileName + ": fileSize: " + fileSize);
this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize);
- return "";
+ return { text: "", fileSize: fileSize };
}
}
- return getText();
+ return { text: getText() };
};
TextStorage.prototype.switchToScriptVersionCache = function () {
if (!this.svc || this.pendingReloadFromDisk) {
@@ -120037,6 +120421,10 @@ var ts;
return this.textStorage.version;
};
/*@internal*/
+ ScriptInfo.prototype.getTelemetryFileSize = function () {
+ return this.textStorage.getTelemetryFileSize();
+ };
+ /*@internal*/
ScriptInfo.prototype.isDynamicOrHasMixedContent = function () {
return this.hasMixedContent || this.isDynamic;
};
@@ -120396,27 +120784,45 @@ var ts;
ProjectKind[ProjectKind["External"] = 2] = "External";
})(ProjectKind = server.ProjectKind || (server.ProjectKind = {}));
/* @internal */
- function countEachFileTypes(infos) {
- var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0, deferred: 0 };
+ function countEachFileTypes(infos, includeSizes) {
+ if (includeSizes === void 0) { includeSizes = false; }
+ var result = {
+ js: 0, jsSize: 0,
+ jsx: 0, jsxSize: 0,
+ ts: 0, tsSize: 0,
+ tsx: 0, tsxSize: 0,
+ dts: 0, dtsSize: 0,
+ deferred: 0, deferredSize: 0,
+ };
for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) {
var info = infos_2[_i];
+ var fileSize = includeSizes ? info.getTelemetryFileSize() : 0;
switch (info.scriptKind) {
case 1 /* JS */:
result.js += 1;
+ result.jsSize += fileSize;
break;
case 2 /* JSX */:
result.jsx += 1;
+ result.jsxSize += fileSize;
break;
case 3 /* TS */:
- ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */)
- ? result.dts += 1
- : result.ts += 1;
+ if (ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */)) {
+ result.dts += 1;
+ result.dtsSize += fileSize;
+ }
+ else {
+ result.ts += 1;
+ result.tsSize += fileSize;
+ }
break;
case 4 /* TSX */:
result.tsx += 1;
+ result.tsxSize += fileSize;
break;
case 7 /* Deferred */:
result.deferred += 1;
+ result.deferredSize += fileSize;
break;
}
}
@@ -120957,7 +121363,7 @@ var ts;
return false;
};
Project.prototype.containsScriptInfo = function (info) {
- return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined);
+ return this.isRoot(info) || (!!this.program && this.program.getSourceFileByPath(info.path) !== undefined);
};
Project.prototype.containsFile = function (filename, requireOpen) {
var info = this.projectService.getScriptInfoForNormalizedPath(filename);
@@ -121149,7 +121555,7 @@ var ts;
return fileWatcher;
};
Project.prototype.isWatchedMissingFile = function (path) {
- return this.missingFilesMap && this.missingFilesMap.has(path);
+ return !!this.missingFilesMap && this.missingFilesMap.has(path);
};
Project.prototype.getScriptInfoForNormalizedPath = function (fileName) {
var scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName));
@@ -121480,6 +121886,8 @@ var ts;
/*lastFileExceededProgramSize*/ undefined,
/*compilerOptions*/ {},
/*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
+ /*@internal*/
+ _this.canConfigFileJsonReportNoInputFiles = false;
/** Ref count to the project when opened from external project */
_this.externalProjectRefCount = 0;
_this.isInitialLoadPending = ts.returnTrue;
@@ -121944,6 +122352,8 @@ var ts;
this.safelist = defaultTypeSafeList;
this.legacySafelist = ts.createMap();
this.pendingProjectUpdates = ts.createMap();
+ /* @internal */
+ this.pendingEnsureProjectForOpenFiles = false;
/** Tracks projects that we have already sent telemetry for. */
this.seenProjects = ts.createMap();
/** Tracks projects that we have already sent survey events for. */
@@ -122889,7 +123299,7 @@ var ts;
setProjectOptionsUsed(project);
var data = {
projectId: this.host.createSHA256Hash(project.projectName),
- fileStats: server.countEachFileTypes(project.getScriptInfos()),
+ fileStats: server.countEachFileTypes(project.getScriptInfos(), /*includeSizes*/ true),
compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()),
typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()),
extends: projectOptions && projectOptions.configHasExtendsProperty,
@@ -123170,7 +123580,7 @@ var ts;
return this.createInferredProject(currentDirectory);
};
ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) {
- var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects;
+ var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; // TODO: GH#18217
var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides);
if (isSingleInferredProject) {
this.inferredProjects.unshift(project);
@@ -125900,7 +126310,7 @@ var ts;
Session.prototype.isLocation = function (locationOrSpan) {
return locationOrSpan.line !== undefined;
};
- Session.prototype.extractPositionAndRange = function (args, scriptInfo) {
+ Session.prototype.extractPositionOrRange = function (args, scriptInfo) {
var position;
var textRange;
if (this.isLocation(args)) {
@@ -125910,7 +126320,7 @@ var ts;
var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition;
textRange = { pos: startPosition, end: endPosition };
}
- return { position: position, textRange: textRange }; // TODO: GH#18217
+ return ts.Debug.assertDefined(position === undefined ? textRange : position);
function getPosition(loc) {
return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset);
}
@@ -125918,14 +126328,12 @@ var ts;
Session.prototype.getApplicableRefactors = function (args) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange;
- return project.getLanguageService().getApplicableRefactors(file, position || textRange, this.getPreferences(file));
+ return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file));
};
Session.prototype.getEditsForRefactor = function (args, simplifiedResult) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var scriptInfo = project.getScriptInfoForNormalizedPath(file);
- var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange;
- var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), position || textRange, args.refactor, args.action, this.getPreferences(file));
+ var result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, this.getPreferences(file));
if (result === undefined) {
return {
edits: []
diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts
index 83a5cab6a59..eb1e1760dfd 100644
--- a/lib/typescript.d.ts
+++ b/lib/typescript.d.ts
@@ -1976,7 +1976,8 @@ declare namespace ts {
AllowEmptyTuple = 524288,
AllowUniqueESSymbolType = 1048576,
AllowEmptyIndexInfoType = 2097152,
- IgnoreErrors = 3112960,
+ AllowNodeModulesRelativePaths = 67108864,
+ IgnoreErrors = 70221824,
InObjectTypeLiteral = 4194304,
InTypeAlias = 8388608,
InInitialEntityName = 16777216,
@@ -3131,7 +3132,6 @@ declare namespace ts {
function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean;
function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner;
}
-/** Non-internal stuff goes here */
declare namespace ts {
function isExternalModuleNameRelative(moduleName: string): boolean;
function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray;
@@ -3478,6 +3478,7 @@ declare namespace ts {
type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail;
function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken;
function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail;
+ function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier;
function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken;
function isModifier(node: Node): node is Modifier;
function isEntityName(node: Node): node is EntityName;
@@ -4867,7 +4868,7 @@ declare namespace ts {
message: string;
position: number;
}
- class TextChange {
+ interface TextChange {
span: TextSpan;
newText: string;
}
diff --git a/lib/typescript.js b/lib/typescript.js
index 9b296e619a2..43953811700 100644
--- a/lib/typescript.js
+++ b/lib/typescript.js
@@ -75,7 +75,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "3.2";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".1";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -3051,13 +3051,15 @@ var ts;
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
- NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors";
+ // Errors (cont.)
+ NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
+ /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
+ NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
// State
NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
- /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain";
})(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
// Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
var TypeFormatFlags;
@@ -5249,7 +5251,7 @@ var ts;
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
- An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."),
+ An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
@@ -5356,7 +5358,7 @@ var ts;
Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
- A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."),
+ A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."),
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
@@ -5439,7 +5441,7 @@ var ts;
_0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
- Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."),
+ Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
@@ -5470,7 +5472,7 @@ var ts;
Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
- Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."),
+ Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
@@ -5515,6 +5517,7 @@ var ts;
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
+ Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
@@ -5614,6 +5617,7 @@ var ts;
Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
+ The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
@@ -6009,6 +6013,7 @@ var ts;
Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
+ Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
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."),
@@ -6104,6 +6109,7 @@ var ts;
Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
+ Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
@@ -6172,6 +6178,9 @@ var ts;
Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"),
Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
+ Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
+ Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
+ Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
};
})(ts || (ts = {}));
var ts;
@@ -6401,11 +6410,28 @@ var ts;
}
ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
/* @internal */
- function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) {
+ function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) {
+ return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true);
+ }
+ ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits;
+ /* @internal */
+ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
if (line < 0 || line >= lineStarts.length) {
- ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ if (allowEdits) {
+ // Clamp line to nearest allowable value
+ line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
+ }
+ else {
+ ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ }
}
var res = lineStarts[line] + character;
+ if (allowEdits) {
+ // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
+ // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
+ // apply them to the computed position to improve accuracy
+ return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
+ }
if (line < lineStarts.length - 1) {
ts.Debug.assert(res < lineStarts[line + 1]);
}
@@ -8057,7 +8083,6 @@ var ts;
}
ts.createScanner = createScanner;
})(ts || (ts = {}));
-/** Non-internal stuff goes here */
var ts;
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -12342,6 +12367,31 @@ var ts;
return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
}
ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
+ function isTypeNodeKind(kind) {
+ return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
+ || kind === 120 /* AnyKeyword */
+ || kind === 143 /* UnknownKeyword */
+ || kind === 135 /* NumberKeyword */
+ || kind === 146 /* BigIntKeyword */
+ || kind === 136 /* ObjectKeyword */
+ || kind === 123 /* BooleanKeyword */
+ || kind === 138 /* StringKeyword */
+ || kind === 139 /* SymbolKeyword */
+ || kind === 100 /* ThisKeyword */
+ || kind === 106 /* VoidKeyword */
+ || kind === 141 /* UndefinedKeyword */
+ || kind === 96 /* NullKeyword */
+ || kind === 132 /* NeverKeyword */
+ || kind === 211 /* ExpressionWithTypeArguments */
+ || kind === 284 /* JSDocAllType */
+ || kind === 285 /* JSDocUnknownType */
+ || kind === 286 /* JSDocNullableType */
+ || kind === 287 /* JSDocNonNullableType */
+ || kind === 288 /* JSDocOptionalType */
+ || kind === 289 /* JSDocFunctionType */
+ || kind === 290 /* JSDocVariadicType */;
+ }
+ ts.isTypeNodeKind = isTypeNodeKind;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13810,6 +13860,10 @@ var ts;
|| kind === 17 /* TemplateTail */;
}
ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
+ function isImportOrExportSpecifier(node) {
+ return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
+ }
+ ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
function isStringTextContainingNode(node) {
return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
}
@@ -13978,37 +14032,13 @@ var ts;
}
ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
// Type
- function isTypeNodeKind(kind) {
- return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
- || kind === 120 /* AnyKeyword */
- || kind === 143 /* UnknownKeyword */
- || kind === 135 /* NumberKeyword */
- || kind === 146 /* BigIntKeyword */
- || kind === 136 /* ObjectKeyword */
- || kind === 123 /* BooleanKeyword */
- || kind === 138 /* StringKeyword */
- || kind === 139 /* SymbolKeyword */
- || kind === 100 /* ThisKeyword */
- || kind === 106 /* VoidKeyword */
- || kind === 141 /* UndefinedKeyword */
- || kind === 96 /* NullKeyword */
- || kind === 132 /* NeverKeyword */
- || kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
- }
/**
* Node test that determines whether a node is a valid type node.
* This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
* of a TypeNode.
*/
function isTypeNode(node) {
- return isTypeNodeKind(node.kind);
+ return ts.isTypeNodeKind(node.kind);
}
ts.isTypeNode = isTypeNode;
function isFunctionOrConstructorTypeNode(node) {
@@ -16529,53 +16559,46 @@ var ts;
return visitNodes(cbNode, cbNodes, node.tags);
case 299 /* JSDocParameterTag */:
case 305 /* JSDocPropertyTag */:
- if (node.isNameFirst) {
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.typeExpression);
- }
- else {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.name);
- }
- case 300 /* JSDocReturnTag */:
- return visitNode(cbNode, node.typeExpression);
- case 302 /* JSDocTypeTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ (node.isNameFirst
+ ? visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.typeExpression)
+ : visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.name));
case 295 /* JSDocAugmentsTag */:
- return visitNode(cbNode, node.class);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.class);
case 303 /* JSDocTemplateTag */:
- return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.constraint) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters);
case 304 /* JSDocTypedefTag */:
- if (node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */) {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.fullName);
- }
- else {
- return visitNode(cbNode, node.fullName) ||
- visitNode(cbNode, node.typeExpression);
- }
+ return visitNode(cbNode, node.tagName) ||
+ (node.typeExpression &&
+ node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ ? visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.fullName)
+ : visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression));
case 297 /* JSDocCallbackTag */:
- return visitNode(cbNode, node.fullName) ||
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
+ case 300 /* JSDocReturnTag */:
+ case 302 /* JSDocTypeTag */:
case 301 /* JSDocThisTag */:
- return visitNode(cbNode, node.typeExpression);
case 298 /* JSDocEnumTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.typeExpression);
case 293 /* JSDocSignature */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- ts.forEach(node.typeParameters, cbNode) ||
+ return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
case 292 /* JSDocTypeLiteral */:
- if (node.jsDocPropertyTags) {
- for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
- var tag = _a[_i];
- visitNode(cbNode, tag);
- }
- }
- return;
+ return ts.forEach(node.jsDocPropertyTags, cbNode);
+ case 294 /* JSDocTag */:
+ case 296 /* JSDocClassTag */:
+ return visitNode(cbNode, node.tagName);
case 308 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
@@ -23278,6 +23301,18 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "diagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_diagnostic_information
+ },
+ {
+ name: "extendedDiagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_verbose_diagnostic_information
+ },
];
/* @internal */
ts.optionDeclarations = ts.commonOptionsWithBuild.concat([
@@ -23741,18 +23776,6 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
},
- {
- name: "diagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_diagnostic_information
- },
- {
- name: "extendedDiagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_verbose_diagnostic_information
- },
{
name: "resolveJsonModule",
type: "boolean",
@@ -28223,6 +28246,7 @@ var ts;
}
}
function bindJSDocTypeAlias(node) {
+ node.tagName.parent = node;
if (node.fullName) {
setParentPointers(node, node.fullName);
}
@@ -29336,7 +29360,7 @@ var ts;
return true;
}
var node = symbol.valueDeclaration;
- if (ts.isCallExpression(node)) {
+ if (node && ts.isCallExpression(node)) {
return !!ts.getAssignedExpandoInitializer(node);
}
var init = !node ? undefined :
@@ -30908,17 +30932,7 @@ var ts;
var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
return parsed ? isImplementationOfOverload(parsed) : undefined;
},
- getImmediateAliasedSymbol: function (symbol) {
- ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
- var links = getSymbolLinks(symbol);
- if (!links.immediateTarget) {
- var node = getDeclarationOfAliasSymbol(symbol);
- if (!node)
- return ts.Debug.fail();
- links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
- }
- return links.immediateTarget;
- },
+ getImmediateAliasedSymbol: getImmediateAliasedSymbol,
getAliasedSymbol: resolveAlias,
getEmitResolver: getEmitResolver,
getExportsOfModule: getExportsOfModuleAsArray,
@@ -30948,6 +30962,7 @@ var ts;
getNumberType: function () { return numberType; },
createPromiseType: createPromiseType,
createArrayType: createArrayType,
+ getElementTypeOfArrayType: getElementTypeOfArrayType,
getBooleanType: function () { return booleanType; },
getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
@@ -31497,7 +31512,11 @@ var ts;
(source.flags | target.flags) & 67108864 /* Assignment */) {
ts.Debug.assert(source !== target);
if (!(target.flags & 33554432 /* Transient */)) {
- target = cloneSymbol(resolveSymbol(target));
+ var resolvedTarget = resolveSymbol(target);
+ if (resolvedTarget === unknownSymbol) {
+ return source;
+ }
+ target = cloneSymbol(resolvedTarget);
}
// Javascript static-property-assignment declarations always merge, even though they are also values
if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
@@ -32756,8 +32775,8 @@ var ts;
undefined;
return initializer || decl;
}
- function resolveExternalModuleName(location, moduleReferenceExpression) {
- return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
+ function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
+ return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0);
}
function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
if (isForAugmentation === void 0) { isForAugmentation = false; }
@@ -32785,7 +32804,7 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
- if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) {
+ if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
}
// merged symbol is module declaration symbol combined with all augmentations
@@ -33056,6 +33075,50 @@ var ts;
function getParentOfSymbol(symbol) {
return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
}
+ function getAlternativeContainingModules(symbol, enclosingDeclaration) {
+ var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
+ var id = "" + getNodeId(containingFile);
+ var links = getSymbolLinks(symbol);
+ var results;
+ if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
+ return results;
+ }
+ if (containingFile && containingFile.imports) {
+ // Try to make an import using an import already in the enclosing file, if possible
+ for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
+ var importRef = _a[_i];
+ if (ts.nodeIsSynthesized(importRef))
+ continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
+ var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
+ if (!resolvedModule)
+ continue;
+ var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, resolvedModule);
+ }
+ if (ts.length(results)) {
+ (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
+ return results;
+ }
+ }
+ if (links.extendedContainers) {
+ return links.extendedContainers;
+ }
+ // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
+ var otherFiles = host.getSourceFiles();
+ for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
+ var file = otherFiles_1[_b];
+ if (!ts.isExternalModule(file))
+ continue;
+ var sym = getSymbolOfNode(file);
+ var ref = getAliasForSymbolInContainer(sym, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, sym);
+ }
+ return links.extendedContainers = results || ts.emptyArray;
+ }
/**
* Attempts to find the symbol corresponding to the container a symbol is in - usually this
* is just its' `.parent`, but for locals, this value is `undefined`
@@ -33064,10 +33127,12 @@ var ts;
var container = getParentOfSymbol(symbol);
if (container) {
var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
+ var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
- return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope
+ return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
}
- return ts.append(additionalContainers, container);
+ var res = ts.append(additionalContainers, container);
+ return ts.concatenate(res, reexportContainers);
}
var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; });
if (!ts.length(candidates)) {
@@ -33506,7 +33571,7 @@ var ts;
}
function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
- var nodeFlags = 3112960 /* IgnoreErrors */;
+ var nodeFlags = 70221824 /* IgnoreErrors */;
if (flags & 2 /* UseOnlyExternalAliasing */) {
nodeFlags |= 128 /* UseOnlyExternalAliasing */;
}
@@ -33517,7 +33582,7 @@ var ts;
nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
}
if (flags & 16 /* DoNotIncludeSymbolChain */) {
- nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */;
+ nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
}
var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
@@ -33540,7 +33605,7 @@ var ts;
else {
sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */;
}
- var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
+ var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217
@@ -33551,7 +33616,7 @@ var ts;
if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
- var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
+ var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
if (typeNode === undefined)
return ts.Debug.fail("should always get typenode");
var options = { removeComments: true };
@@ -33602,7 +33667,7 @@ var ts;
enclosingDeclaration: enclosingDeclaration,
flags: flags || 0 /* None */,
// If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
- tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? {
+ tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
getSourceFiles: function () { return host.getSourceFiles(); },
getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); })
@@ -33855,11 +33920,7 @@ var ts;
return symbolToTypeNode(typeAlias, context, 67897832 /* Type */);
}
else {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
}
else {
@@ -33873,11 +33934,7 @@ var ts;
}
var depth = context.symbolDepth.get(id) || 0;
if (depth > 10) {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
context.symbolDepth.set(id, depth + 1);
context.visitedTypes.set(typeId, true);
@@ -34062,10 +34119,15 @@ var ts;
typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context));
}
if (resolvedType.stringIndexInfo) {
- var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ?
- createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) :
- resolvedType.stringIndexInfo;
- typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context));
+ var indexSignature = void 0;
+ if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
+ indexSignature.type = createElidedInformationPlaceholder(context);
+ }
+ else {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
+ }
+ typeElements.push(indexSignature);
}
if (resolvedType.numberIndexInfo) {
typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
@@ -34096,8 +34158,16 @@ var ts;
return typeElements.length ? typeElements : undefined;
}
}
+ function createElidedInformationPlaceholder(context) {
+ context.approximateLength += 3;
+ if (!(context.flags & 1 /* NoTruncation */)) {
+ return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
+ }
+ return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
function addPropertyToElementList(propertySymbol, context, typeElements) {
- var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ?
+ var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */);
+ var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
anyType : getTypeOfSymbol(propertySymbol);
var saveEnclosingDeclaration = context.enclosingDeclaration;
context.enclosingDeclaration = undefined;
@@ -34127,8 +34197,14 @@ var ts;
}
else {
var savedFlags = context.flags;
- context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0;
- var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
+ var propertyTypeNode = void 0;
+ if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
+ propertyTypeNode = createElidedInformationPlaceholder(context);
+ }
+ else {
+ propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
context.flags = savedFlags;
var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined;
if (modifiers) {
@@ -34314,7 +34390,7 @@ var ts;
// Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
var chain;
var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
- if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) {
+ if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
ts.Debug.assert(chain && chain.length > 0);
}
@@ -34325,13 +34401,22 @@ var ts;
/** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
function getSymbolChain(symbol, meaning, endOfChain) {
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
+ var parentSpecifiers;
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
// Go up and add our parent.
- var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
- if (ts.length(parents)) {
- for (var _i = 0, _a = parents; _i < _a.length; _i++) {
- var parent = _a[_i];
+ var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
+ if (ts.length(parents_1)) {
+ parentSpecifiers = parents_1.map(function (symbol) {
+ return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
+ ? getSpecifierForModuleSymbol(symbol, context)
+ : undefined;
+ });
+ var indices = parents_1.map(function (_, i) { return i; });
+ indices.sort(sortByBestName);
+ var sortedParents = indices.map(function (i) { return parents_1[i]; });
+ for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
+ var parent = sortedParents_1[_i];
var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
if (parentChain) {
accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
@@ -34354,6 +34439,24 @@ var ts;
}
return [symbol];
}
+ function sortByBestName(a, b) {
+ var specifierA = parentSpecifiers[a];
+ var specifierB = parentSpecifiers[b];
+ if (specifierA && specifierB) {
+ var isBRelative = ts.pathIsRelative(specifierB);
+ if (ts.pathIsRelative(specifierA) === isBRelative) {
+ // Both relative or both non-relative, sort by number of parts
+ return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
+ }
+ if (isBRelative) {
+ // A is non-relative, B is relative: prefer A
+ return -1;
+ }
+ // A is relative, B is non-relative: prefer B
+ return 1;
+ }
+ return 0;
+ }
}
}
function typeParametersToTypeParameterDeclarations(symbol, context) {
@@ -34442,6 +34545,14 @@ var ts;
var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
var specifier = getSpecifierForModuleSymbol(chain[0], context);
+ if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
+ // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
+ // since declaration files with these kinds of references are liable to fail when published :(
+ context.encounteredError = true;
+ if (context.tracker.reportLikelyUnsafeImportRequiredError) {
+ context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
+ }
+ }
var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
@@ -34578,7 +34689,7 @@ var ts;
if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
function typePredicateToStringWorker(writer) {
- var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
+ var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
var printer = ts.createPrinter({ removeComments: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
@@ -36003,7 +36114,7 @@ var ts;
return type.resolvedBaseTypes = ts.emptyArray;
}
if (!isValidBaseType(baseType)) {
- error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType));
+ error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType));
return type.resolvedBaseTypes = ts.emptyArray;
}
if (type === baseType || hasBaseType(baseType, type)) {
@@ -36059,7 +36170,7 @@ var ts;
}
}
else {
- error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface);
+ error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -39359,7 +39470,7 @@ var ts;
if (accessExpression) {
markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */);
if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) {
- error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop));
+ error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
return missingType;
}
if (cacheSymbol) {
@@ -41623,7 +41734,8 @@ var ts;
var bestMatchingType = findMatchingDiscriminantType(source, target) ||
findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
findBestTypeForObjectLiteral(source, target) ||
- findBestTypeForInvokable(source, target);
+ findBestTypeForInvokable(source, target) ||
+ findMostOverlappyType(source, target);
isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
}
return 0 /* False */;
@@ -41658,6 +41770,34 @@ var ts;
return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
}
}
+ function findMostOverlappyType(source, unionTarget) {
+ var bestMatch;
+ var matchingCount = 0;
+ for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
+ var target_1 = _a[_i];
+ var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]);
+ if (overlap.flags & 4194304 /* Index */) {
+ // perfect overlap of keys
+ bestMatch = target_1;
+ matchingCount = Infinity;
+ }
+ else if (overlap.flags & 1048576 /* Union */) {
+ // Some subset overlap if we have only string literals.
+ // If we have a union of index types, it seems likely that we
+ // needed to elaborate between two generic mapped types anyway.
+ var len = ts.length(overlap.types);
+ if (len >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = len;
+ }
+ }
+ else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = 1;
+ }
+ }
+ return bestMatch;
+ }
// Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
function findMatchingDiscriminantType(source, target) {
if (target.flags & 1048576 /* Union */) {
@@ -42760,12 +42900,8 @@ var ts;
return true;
}
// A source signature partially matches a target signature if the target signature has no fewer required
- // parameters and no more overall parameters than the source signature (where a signature with a rest
- // parameter is always considered to have more overall parameters than one without).
- var sourceRestCount = sourceHasRestParameter ? 1 : 0;
- var targetRestCount = targetHasRestParameter ? 1 : 0;
- if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount ||
- sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) {
+ // parameters
+ if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
return true;
}
return false;
@@ -42871,6 +43007,9 @@ var ts;
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
}
+ function getElementTypeOfArrayType(type) {
+ return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined;
+ }
function isArrayLikeType(type) {
// A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
// or if it is not the undefined or null type and if it is assignable to ReadonlyArray
@@ -43243,6 +43382,16 @@ var ts;
diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
break;
case 151 /* Parameter */:
+ var param = declaration;
+ if (ts.isIdentifier(param.name) &&
+ (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
+ param.parent.parameters.indexOf(param) > -1 &&
+ (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
+ param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
+ var newName = "arg" + param.parent.parameters.indexOf(param);
+ errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
+ return;
+ }
diagnostic = declaration.dotDotDotToken ?
noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage :
noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
@@ -45644,7 +45793,12 @@ var ts;
return errorType;
}
if (isReadonlySymbol(localOrExportSymbol)) {
- error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol));
+ if (localOrExportSymbol.flags & 3 /* Variable */) {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
+ }
+ else {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
+ }
return errorType;
}
}
@@ -47129,6 +47283,17 @@ var ts;
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
return createIndexInfo(unionType, /*isReadonly*/ false);
}
+ function getImmediateAliasedSymbol(symbol) {
+ ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
+ var links = getSymbolLinks(symbol);
+ if (!links.immediateTarget) {
+ var node = getDeclarationOfAliasSymbol(symbol);
+ if (!node)
+ return ts.Debug.fail();
+ links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
+ }
+ return links.immediateTarget;
+ }
function checkObjectLiteral(node, checkMode) {
var inDestructuringPattern = ts.isAssignmentTarget(node);
// Grammar checking
@@ -47596,16 +47761,31 @@ var ts;
function getJsxElementChildrenPropertyName(jsxNamespace) {
return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
- function getUninstantiatedJsxSignaturesOfType(elementType) {
+ function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
+ if (elementType.flags & 4 /* String */) {
+ return [anySignature];
+ }
+ else if (elementType.flags & 128 /* StringLiteral */) {
+ var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
+ if (!intrinsicType) {
+ error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
+ return ts.emptyArray;
+ }
+ else {
+ var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
+ return [fakeSignature];
+ }
+ }
+ var apparentElemType = getApparentType(elementType);
// Resolve the signatures, preferring constructor
- var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
+ var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
if (signatures.length === 0) {
// No construct signatures, try call signatures
- signatures = getSignaturesOfType(elementType, 0 /* Call */);
+ signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
}
- if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) {
+ if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
// If each member has some combination of new/call signatures; make a union signature list for those
- signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType));
+ signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
}
return signatures;
}
@@ -47978,7 +48158,7 @@ var ts;
checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop);
if (assignmentKind) {
if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) {
- error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right));
+ error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
return errorType;
}
}
@@ -49546,20 +49726,8 @@ var ts;
if (apparentType === errorType) {
return resolveErrorCall(node);
}
- if (exprTypes.flags & 128 /* StringLiteral */) {
- var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node);
- if (!intrinsicType) {
- error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements);
- return resolveUntypedCall(node);
- }
- else {
- var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes);
- return fakeSignature;
- }
- }
- var signatures = getUninstantiatedJsxSignaturesOfType(apparentType);
- if (exprTypes.flags & 4 /* String */ || isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
+ var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
+ if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
return resolveUntypedCall(node);
}
if (signatures.length === 0) {
@@ -51184,8 +51352,17 @@ var ts;
leftType;
case 59 /* EqualsToken */:
var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
- checkAssignmentDeclaration(declKind, right);
+ checkAssignmentDeclaration(declKind, rightType);
if (isAssignmentDeclaration(declKind)) {
+ if (!(rightType.flags & 524288 /* Object */) ||
+ declKind !== 2 /* ModuleExports */ &&
+ declKind !== 6 /* Prototype */ &&
+ !isEmptyObjectType(rightType) &&
+ !isFunctionObjectType(rightType) &&
+ !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
+ // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
+ checkAssignmentOperator(rightType);
+ }
return leftType;
}
else {
@@ -51200,10 +51377,9 @@ var ts;
default:
return ts.Debug.fail();
}
- function checkAssignmentDeclaration(kind, right) {
+ function checkAssignmentDeclaration(kind, rightType) {
if (kind === 2 /* ModuleExports */) {
- var rightType_1 = checkExpression(right, checkMode);
- for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
var prop = _a[_i];
var propType = getTypeOfSymbol(prop);
if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
@@ -53268,7 +53444,7 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
- if (produceDiagnostics) {
+ if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
@@ -53289,9 +53465,6 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 241 /* InterfaceDeclaration */:
- checkUnusedTypeParameters(node, addDiagnostic);
- break;
case 279 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
@@ -53308,7 +53481,7 @@ var ts;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- if (node.body) {
+ if (node.body) { // Don't report unused parameters in overloads
checkUnusedLocalsAndParameters(node, addDiagnostic);
}
checkUnusedTypeParameters(node, addDiagnostic);
@@ -53319,9 +53492,12 @@ var ts;
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 242 /* TypeAliasDeclaration */:
- case 176 /* InferType */:
+ case 241 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 176 /* InferType */:
+ checkUnusedInferTypeParameter(node, addDiagnostic);
+ break;
default:
ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
}
@@ -53336,77 +53512,73 @@ var ts;
return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
}
function checkUnusedClassMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
- var member = _a[_i];
- switch (member.kind) {
- case 156 /* MethodDeclaration */:
- case 154 /* PropertyDeclaration */:
- case 158 /* GetAccessor */:
- case 159 /* SetAccessor */:
- if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
- // Already would have reported an error on the getter.
- break;
- }
- var symbol = getSymbolOfNode(member);
- if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
- addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
- }
+ for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ switch (member.kind) {
+ case 156 /* MethodDeclaration */:
+ case 154 /* PropertyDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
+ // Already would have reported an error on the getter.
break;
- case 157 /* Constructor */:
- for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
- var parameter = _c[_b];
- if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
- addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
- }
+ }
+ var symbol = getSymbolOfNode(member);
+ if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
+ addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
+ }
+ break;
+ case 157 /* Constructor */:
+ for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
+ var parameter = _c[_b];
+ if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
+ addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
}
- break;
- case 162 /* IndexSignature */:
- case 217 /* SemicolonClassElement */:
- // Can't be private
- break;
- default:
- ts.Debug.fail();
- }
+ }
+ break;
+ case 162 /* IndexSignature */:
+ case 217 /* SemicolonClassElement */:
+ // Can't be private
+ break;
+ default:
+ ts.Debug.fail();
}
}
}
+ function checkUnusedInferTypeParameter(node, addDiagnostic) {
+ var typeParameter = node.typeParameter;
+ if (isTypeParameterUnused(typeParameter)) {
+ addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ }
+ }
function checkUnusedTypeParameters(node, addDiagnostic) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
- if (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node)
+ if (ts.last(getSymbolOfNode(node).declarations) !== node)
return;
- if (node.kind === 176 /* InferType */) {
- var typeParameter = node.typeParameter;
- if (isTypeParameterUnused(typeParameter)) {
- addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
+ var seenParentsWithEveryUnused = new ts.NodeSet();
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var typeParameter = typeParameters_2[_i];
+ if (!isTypeParameterUnused(typeParameter))
+ continue;
+ var name = ts.idText(typeParameter.name);
+ var parent = typeParameter.parent;
+ if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
+ if (seenParentsWithEveryUnused.tryAdd(parent)) {
+ var range = ts.isJSDocTemplateTag(parent)
+ // Whole @template tag
+ ? ts.rangeOfNode(parent)
+ // Include the `<>` in the error message
+ : ts.rangeOfTypeParameters(parent.typeParameters);
+ var only = typeParameters.length === 1;
+ var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
+ var arg0 = only ? name : undefined;
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
+ }
}
- }
- else {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
- if (!isTypeParameterUnused(typeParameter))
- continue;
- var name = ts.idText(typeParameter.name);
- var parent = typeParameter.parent;
- if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
- if (seenParentsWithEveryUnused.tryAdd(parent)) {
- var range = ts.isJSDocTemplateTag(parent)
- // Whole @template tag
- ? ts.rangeOfNode(parent)
- // Include the `<>` in the error message
- : ts.rangeOfTypeParameters(parent.typeParameters);
- var only = typeParameters.length === 1;
- var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
- var arg0 = only ? name : undefined;
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
- }
- }
- else {
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
- }
+ else {
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
}
}
}
@@ -53827,9 +53999,9 @@ var ts;
var nameText = ts.getTextOfPropertyName(name);
if (nameText) {
var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217
- markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
- if (parent.initializer && property) {
- checkPropertyAccessibility(parent, parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
+ if (property) {
+ markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
+ checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
}
}
}
@@ -54887,7 +55059,7 @@ var ts;
}
}
else {
- error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface);
+ error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -56493,7 +56665,10 @@ var ts;
}
if (isDeclarationNameOrImportPropertyName(node)) {
// This is a declaration, call getSymbolOfNode
- return getSymbolOfNode(parent);
+ var parentSymbol = getSymbolOfNode(parent);
+ return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
+ ? getImmediateAliasedSymbol(parentSymbol)
+ : parentSymbol;
}
else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
return getSymbolOfNode(parent.parent);
@@ -64701,7 +64876,7 @@ var ts;
};
function processMapping(mapping) {
var generatedPosition = generatedFile !== undefined
- ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
: -1;
var source;
var sourcePosition;
@@ -64710,7 +64885,7 @@ var ts;
var sourceFile = host.getSourceFileLike(sourceFilePath);
source = map.sources[mapping.sourceIndex];
sourcePosition = sourceFile !== undefined
- ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
: -1;
}
return {
@@ -79700,6 +79875,7 @@ var ts;
reportInaccessibleThisError: reportInaccessibleThisError,
reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
+ reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
moduleResolverHost: host,
trackReferencedAmbientModule: trackReferencedAmbientModule,
trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode
@@ -79788,6 +79964,11 @@ var ts;
context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
}
}
+ function reportLikelyUnsafeImportRequiredError(specifier) {
+ if (errorNameNode) {
+ context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
+ }
+ }
function transformRoot(node) {
if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
@@ -82775,7 +82956,7 @@ var ts;
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
function emitClassExpression(node) {
@@ -83513,7 +83694,7 @@ var ts;
}
function emitSpreadAssignment(node) {
if (node.expression) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
}
@@ -85483,7 +85664,7 @@ var ts;
var text;
try {
ts.performance.mark("beforeIORead");
- text = system.readFile(fileName, options.charset);
+ text = compilerHost.readFile(fileName);
ts.performance.mark("afterIORead");
ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
@@ -85509,7 +85690,12 @@ var ts;
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
- system.createDirectory(directoryPath);
+ if (compilerHost.createDirectory) {
+ compilerHost.createDirectory(directoryPath);
+ }
+ else {
+ system.createDirectory(directoryPath);
+ }
}
}
var outputFingerprints;
@@ -85561,7 +85747,7 @@ var ts;
}
var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
var realpath = system.realpath && (function (path) { return system.realpath(path); });
- return {
+ var compilerHost = {
getSourceFile: getSourceFile,
getDefaultLibLocation: getDefaultLibLocation,
getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
@@ -85577,10 +85763,113 @@ var ts;
getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return system.getDirectories(path); },
realpath: realpath,
- readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }
+ readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
+ createDirectory: function (d) { return system.createDirectory(d); }
};
+ return compilerHost;
}
ts.createCompilerHostWorker = createCompilerHostWorker;
+ /*@internal*/
+ function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) {
+ var originalReadFile = host.readFile;
+ var originalFileExists = host.fileExists;
+ var originalDirectoryExists = host.directoryExists;
+ var originalCreateDirectory = host.createDirectory;
+ var originalWriteFile = host.writeFile;
+ var originalGetSourceFile = host.getSourceFile;
+ var readFileCache = ts.createMap();
+ var fileExistsCache = ts.createMap();
+ var directoryExistsCache = ts.createMap();
+ var sourceFileCache = ts.createMap();
+ var readFileWithCache = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value || undefined;
+ return setReadFileCache(key, fileName);
+ };
+ var setReadFileCache = function (key, fileName) {
+ var newValue = originalReadFile.call(host, fileName);
+ readFileCache.set(key, newValue || false);
+ return newValue;
+ };
+ host.readFile = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value; // could be .d.ts from output
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return originalReadFile.call(host, fileName);
+ }
+ return setReadFileCache(key, fileName);
+ };
+ if (useCacheForSourceFile) {
+ host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
+ var key = toPath(fileName);
+ var value = sourceFileCache.get(key);
+ if (value)
+ return value;
+ var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile);
+ if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
+ sourceFileCache.set(key, sourceFile);
+ }
+ return sourceFile;
+ };
+ }
+ // fileExists for any kind of extension
+ host.fileExists = function (fileName) {
+ var key = toPath(fileName);
+ var value = fileExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalFileExists.call(host, fileName);
+ fileExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
+ var key = toPath(fileName);
+ fileExistsCache.delete(key);
+ var value = readFileCache.get(key);
+ if (value && value !== data) {
+ readFileCache.delete(key);
+ sourceFileCache.delete(key);
+ }
+ else if (useCacheForSourceFile) {
+ var sourceFile = sourceFileCache.get(key);
+ if (sourceFile && sourceFile.text !== data) {
+ sourceFileCache.delete(key);
+ }
+ }
+ originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
+ };
+ // directoryExists
+ if (originalDirectoryExists && originalCreateDirectory) {
+ host.directoryExists = function (directory) {
+ var key = toPath(directory);
+ var value = directoryExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalDirectoryExists.call(host, directory);
+ directoryExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.createDirectory = function (directory) {
+ var key = toPath(directory);
+ directoryExistsCache.delete(key);
+ originalCreateDirectory.call(host, directory);
+ };
+ }
+ return {
+ originalReadFile: originalReadFile,
+ originalFileExists: originalFileExists,
+ originalDirectoryExists: originalDirectoryExists,
+ originalCreateDirectory: originalCreateDirectory,
+ originalWriteFile: originalWriteFile,
+ originalGetSourceFile: originalGetSourceFile,
+ readFileWithCache: readFileWithCache
+ };
+ }
+ ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache;
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (ts.getEmitDeclarations(program.getCompilerOptions())) {
@@ -85967,6 +86256,7 @@ var ts;
// A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
var resolvedProjectReferences;
var projectReferenceRedirects;
+ var mapFromFileToProjectReferenceRedirects;
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2 /* Completely */) {
@@ -87325,15 +87615,20 @@ var ts;
* Get the referenced project if the file is input file from that reference project
*/
function getResolvedProjectReferenceToRedirect(fileName) {
- return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
- // not input file from the referenced project, ignore
- if (!referencedProject ||
- toPath(options.configFilePath) === referenceProjectPath ||
- !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) {
- return undefined;
- }
- return referencedProject;
- });
+ if (mapFromFileToProjectReferenceRedirects === undefined) {
+ mapFromFileToProjectReferenceRedirects = ts.createMap();
+ forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
+ // not input file from the referenced project, ignore
+ if (referencedProject &&
+ toPath(options.configFilePath) !== referenceProjectPath) {
+ referencedProject.commandLine.fileNames.forEach(function (f) {
+ return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
+ });
+ }
+ });
+ }
+ var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
+ return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
}
function forEachResolvedProjectReference(cb) {
return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
@@ -89696,6 +89991,7 @@ var ts;
}
return count;
}
+ moduleSpecifiers.countPathComponents = countPathComponents;
function usesJsExtensionOnImports(_a) {
var imports = _a.imports;
return ts.firstDefined(imports, function (_a) {
@@ -90903,6 +91199,7 @@ var ts;
var missingRoots = ts.createMap();
var globalDependencyGraph;
var writeFileName = function (s) { return host.trace && host.trace(s); };
+ var readFileWithCache = function (f) { return host.readFile(f); };
// Watch state
var diagnostics = createFileMap(toPath);
var projectPendingBuild = createFileMap(toPath);
@@ -91438,19 +91735,15 @@ var ts;
options: configFile.options,
configFileParsingDiagnostics: configFile.errors
};
+ if (host.beforeCreateProgram) {
+ host.beforeCreateProgram(options);
+ }
var program = ts.createProgram(programOptions);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
}
- // Don't emit .d.ts if there are decl file errors
- if (ts.getEmitDeclarations(program.getCompilerOptions())) {
- var declDiagnostics = program.getDeclarationDiagnostics();
- if (declDiagnostics.length) {
- return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
- }
- }
// Same as above but now for semantic diagnostics
var semanticDiagnostics = program.getSemanticDiagnostics();
if (semanticDiagnostics.length) {
@@ -91458,27 +91751,37 @@ var ts;
}
var newestDeclarationFileContentChangedTime = minimumDate;
var anyDtsChanged = false;
- var emitDiagnostics;
- var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); };
- ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) {
+ var declDiagnostics;
+ var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
+ var outputFiles = [];
+ ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); });
+ // Don't emit .d.ts if there are decl file errors
+ if (declDiagnostics) {
+ return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
+ }
+ // Actual Emit
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
var priorChangeTime;
- if (!anyDtsChanged && isDeclarationFile(fileName)) {
+ if (!anyDtsChanged && isDeclarationFile(name)) {
// Check for unchanged .d.ts files
- if (host.fileExists(fileName) && host.readFile(fileName) === content) {
- priorChangeTime = host.getModifiedTime(fileName);
+ if (host.fileExists(name) && readFileWithCache(name) === text) {
+ priorChangeTime = host.getModifiedTime(name);
}
else {
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
anyDtsChanged = true;
}
}
- host.writeFile(fileName, content, writeBom, onError, ts.emptyArray);
+ ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark);
if (priorChangeTime !== undefined) {
newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
- unchangedOutputs.setValue(fileName, priorChangeTime);
+ unchangedOutputs.setValue(name, priorChangeTime);
}
});
- if (emitDiagnostics) {
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
}
var status = {
@@ -91487,11 +91790,17 @@ var ts;
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
}
}
@@ -91558,11 +91867,16 @@ var ts;
if (options.watch) {
reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode);
}
+ // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api
+ // Override readFile for json files and output .d.ts to cache the text
+ var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache;
+ var savedReadFileWithCache = readFileWithCache;
+ readFileWithCache = newReadFileWithCache;
var graph = getGlobalDependencyGraph();
reportBuildQueue(graph);
var anyFailed = false;
- for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
- var next = _a[_i];
+ for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) {
+ var next = _b[_i];
var proj = parseConfigFile(next);
if (proj === undefined) {
reportParseConfigFileDiagnostic(next);
@@ -91604,6 +91918,13 @@ var ts;
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
+ host.readFile = originalReadFile;
+ host.fileExists = originalFileExists;
+ host.directoryExists = originalDirectoryExists;
+ host.createDirectory = originalCreateDirectory;
+ host.writeFile = originalWriteFile;
+ readFileWithCache = savedReadFileWithCache;
+ host.getSourceFile = originalGetSourceFile;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
function reportParseConfigFileDiagnostic(proj) {
@@ -92200,12 +92521,6 @@ var ts;
})(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {}));
/* @internal */
ts.emptyOptions = {};
- var TextChange = /** @class */ (function () {
- function TextChange() {
- }
- return TextChange;
- }());
- ts.TextChange = TextChange;
var HighlightSpanKind;
(function (HighlightSpanKind) {
HighlightSpanKind["none"] = "none";
@@ -92669,6 +92984,10 @@ var ts;
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
ts.isLabelName = isLabelName;
+ function isTagName(node) {
+ return ts.isJSDocTag(node.parent) && node.parent.tagName === node;
+ }
+ ts.isTagName = isTagName;
function isRightSideOfQualifiedName(node) {
return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node;
}
@@ -93559,6 +93878,7 @@ var ts;
ts.createTextChange = createTextChange;
ts.typeKeywords = [
120 /* AnyKeyword */,
+ 146 /* BigIntKeyword */,
123 /* BooleanKeyword */,
87 /* FalseKeyword */,
129 /* KeyOfKeyword */,
@@ -93992,9 +94312,7 @@ var ts;
}
ts.signatureToDisplayParts = signatureToDisplayParts;
function isImportOrExportSpecifierName(location) {
- return !!location.parent &&
- (location.parent.kind === 253 /* ImportSpecifier */ || location.parent.kind === 257 /* ExportSpecifier */) &&
- location.parent.propertyName === location;
+ return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location;
}
ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
/**
@@ -95416,26 +95734,21 @@ var ts;
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
*/
- function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) {
+ function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) {
// Make all paths absolute/normalized if they are not already
rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); });
// Determine the path to the directory containing the script relative to the root directory it is contained within
var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) {
- return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined;
+ return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined;
}); // TODO: GH#18217
// Now find a path for each potential directory that is to be merged with the one containing the script
- return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
}
- function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensionOptions, compilerOptions, host, exclude) {
+ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) {
var basePath = compilerOptions.project || host.getCurrentDirectory();
var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
- var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase);
- var result = [];
- for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) {
- var baseDirectory = baseDirectories_1[_i];
- getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude, result);
- }
- return result;
+ var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
+ return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); });
}
/**
* Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
@@ -96666,7 +96979,8 @@ var ts;
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
isInSnippetScope = isSnippetScope(scopeNode);
- var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
+ var isTypeOnly = isTypeOnlyCompletion();
+ var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) {
@@ -96715,9 +97029,9 @@ var ts;
}
}
function filterGlobalCompletion(symbols) {
- var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
- var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
- if (isTypeOnlyCompletion)
+ var isTypeOnly = isTypeOnlyCompletion();
+ var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
+ if (isTypeOnly)
keywordFilters = 6 /* TypeKeywords */;
ts.filterMutate(symbols, function (symbol) {
if (!ts.isSourceFile(location)) {
@@ -96733,7 +97047,7 @@ var ts;
if (allowTypes) {
// Its a type, but you can reach it by namespace.type as well
var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol);
- if (symbolAllowedAsType || isTypeOnlyCompletion) {
+ if (symbolAllowedAsType || isTypeOnly) {
return symbolAllowedAsType;
}
}
@@ -96742,6 +97056,9 @@ var ts;
return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */);
});
}
+ function isTypeOnlyCompletion() {
+ return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
+ }
function isContextTokenValueLocation(contextToken) {
return contextToken &&
contextToken.kind === 104 /* TypeOfKeyword */ &&
@@ -97127,6 +97444,7 @@ var ts;
if (contextToken) {
var parent = contextToken.parent;
switch (contextToken.kind) {
+ case 30 /* GreaterThanToken */: // End of a type argument list
case 29 /* LessThanSlashToken */:
case 42 /* SlashToken */:
case 72 /* Identifier */:
@@ -97135,6 +97453,11 @@ var ts;
case 267 /* JsxAttribute */:
case 269 /* JsxSpreadAttribute */:
if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) {
+ if (contextToken.kind === 30 /* GreaterThanToken */) {
+ var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined);
+ if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */))
+ break;
+ }
return parent;
}
else if (parent.kind === 267 /* JsxAttribute */) {
@@ -98553,7 +98876,7 @@ var ts;
return undefined;
}
var lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
- return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false };
+ return { kind: 0 /* Import */, symbol: lhsSymbol };
}
else {
return exportInfo(symbol, getExportKindForDeclaration(exportNode));
@@ -98623,7 +98946,7 @@ var ts;
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
- return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
+ return { kind: 0 /* Import */, symbol: importedSymbol };
}
}
function exportInfo(symbol, kind) {
@@ -98668,18 +98991,16 @@ var ts;
var parent = node.parent;
switch (parent.kind) {
case 248 /* ImportEqualsDeclaration */:
- return parent.name === node && isExternalModuleImportEquals(parent)
- ? { isNamedImport: false }
- : undefined;
+ return parent.name === node && isExternalModuleImportEquals(parent);
case 253 /* ImportSpecifier */:
// For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
- return parent.propertyName ? undefined : { isNamedImport: true };
+ return !parent.propertyName;
case 250 /* ImportClause */:
case 251 /* NamespaceImport */:
ts.Debug.assert(parent.name === node);
- return { isNamedImport: false };
+ return true;
default:
- return undefined;
+ return false;
}
}
function getExportInfo(exportSymbol, exportKind, checker) {
@@ -98797,7 +99118,7 @@ var ts;
}
}
function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) {
- return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); });
+ return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); });
}
FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries;
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
@@ -98851,8 +99172,8 @@ var ts;
var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
return { displayParts: displayParts, kind: symbolKind };
}
- function toRenameLocation(entry, originalNode) {
- return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode));
+ function toRenameLocation(entry, originalNode, checker) {
+ return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker));
}
FindAllReferences.toRenameLocation = toRenameLocation;
function toReferenceEntry(entry) {
@@ -98881,25 +99202,27 @@ var ts;
return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName };
}
}
- function getPrefixAndSuffixText(entry, originalNode) {
+ function getPrefixAndSuffixText(entry, originalNode, checker) {
if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) {
var node = entry.node, kind = entry.kind;
var name = originalNode.text;
var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent);
if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) {
- if (kind === 3 /* SearchedLocalFoundProperty */) {
- return { prefixText: name + ": " };
- }
- else if (kind === 4 /* SearchedPropertyFoundLocal */) {
- return { suffixText: ": " + name };
- }
- else {
- return isShorthandAssignment
+ var prefixColon = { prefixText: name + ": " };
+ var suffixColon = { suffixText: ": " + name };
+ return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon
+ : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon
// In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol.
- ? { suffixText: ": " + name }
// For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol.
- : { prefixText: name + ": " };
- }
+ : isShorthandAssignment ? suffixColon : prefixColon;
+ }
+ else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
+ // If the original symbol was using this alias, just rename the alias.
+ var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
+ return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions;
+ }
+ else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
+ return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name };
}
}
return ts.emptyOptions;
@@ -99154,13 +99477,18 @@ var ts;
return undefined;
}
/** Core find-all-references algorithm for a normal symbol. */
- function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
- symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
+ function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
+ var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol;
// Compute the meaning from the location and the symbol it references
var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
var result = [];
var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
- if (node && node.kind === 80 /* DefaultKeyword */) {
+ var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier);
+ if (exportSpecifier) {
+ // When renaming at an export specifier, rename the export and not the thing being exported.
+ getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true);
+ }
+ else if (node && node.kind === 80 /* DefaultKeyword */) {
addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
@@ -99198,15 +99526,11 @@ var ts;
}
}
/** Handle a few special cases relating to export/import specifiers. */
- function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) {
+ function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) {
var parent = node.parent;
- if (ts.isExportSpecifier(parent)) {
+ if (ts.isExportSpecifier(parent) && !isForRename) {
return getLocalSymbolForExportSpecifier(node, symbol, parent, checker);
}
- if (ts.isImportSpecifier(parent) && parent.propertyName === node) {
- // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import.
- return checker.getImmediateAliasedSymbol(symbol);
- }
// If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references.
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
@@ -99369,7 +99693,8 @@ var ts;
var indirectUser = indirectUsers_2[_b];
for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) {
var node = _d[_c];
- if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) {
+ // Import specifiers should be handled by importSearches
+ if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) {
cb(node);
}
}
@@ -99385,7 +99710,7 @@ var ts;
if (!ts.isIdentifier(singleRef))
return false;
// At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */);
+ return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */);
}
// Go to the symbol we imported from and find references for it.
function searchForImportedSymbol(symbol, state) {
@@ -99664,16 +99989,16 @@ var ts;
}
getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
}
- function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) {
+ function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) {
var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
var exportDeclaration = parent.parent;
var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
- if (!search.includes(localSymbol)) {
+ if (!alwaysGetReferences && !search.includes(localSymbol)) {
return;
}
if (!propertyName) {
// Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export)
- if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) {
+ if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) {
addRef();
}
}
@@ -99684,7 +100009,7 @@ var ts;
addRef();
}
if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) {
- addReference(name, referenceSymbol, state);
+ addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state);
}
}
else {
@@ -99693,15 +100018,14 @@ var ts;
}
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
- if (!(referenceLocation === propertyName && state.options.isForRename)) {
+ if (!state.options.isForRename || alwaysGetReferences) {
var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
- var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker);
- if (!exportInfo)
- return ts.Debug.fail();
- searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state);
+ var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
+ var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker));
+ searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
}
// At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
- if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) {
+ if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) {
var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
if (imported)
searchForImportedSymbol(imported, state);
@@ -99733,12 +100057,11 @@ var ts;
return;
var symbol = importOrExport.symbol;
if (importOrExport.kind === 0 /* Import */) {
- if (!state.options.isForRename || importOrExport.isNamedImport) {
+ if (!state.options.isForRename) {
searchForImportedSymbol(symbol, state);
}
}
else {
- // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching.
searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
}
}
@@ -103736,7 +104059,7 @@ var ts;
function getEnclosingDeclarationFromInvocation(invocation) {
return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
}
- var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
+ var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) {
var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
@@ -104902,16 +105225,11 @@ var ts;
this.options = options;
}
FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
- ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null");
- ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null");
- ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null");
- ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null");
- ts.Debug.assert(commonParent !== undefined, "commonParent is null");
- this.currentTokenSpan = currentRange;
- this.currentTokenParent = currentTokenParent;
- this.nextTokenSpan = nextRange;
- this.nextTokenParent = nextTokenParent;
- this.contextNode = commonParent;
+ this.currentTokenSpan = ts.Debug.assertDefined(currentRange);
+ this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent);
+ this.nextTokenSpan = ts.Debug.assertDefined(nextRange);
+ this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent);
+ this.contextNode = ts.Debug.assertDefined(commonParent);
// drop cached results
this.contextNodeAllOnSameLine = undefined;
this.nextNodeAllOnSameLine = undefined;
@@ -107637,7 +107955,6 @@ var ts;
};
ChangeTracker.prototype.deleteRange = function (sourceFile, range) {
this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range });
- return this;
};
ChangeTracker.prototype.delete = function (sourceFile, node) {
this.deletedNodes.push({ sourceFile: sourceFile, node: node });
@@ -107650,7 +107967,6 @@ var ts;
var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
- return this;
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
if (options === void 0) { options = {}; }
@@ -107661,11 +107977,10 @@ var ts;
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
if (options === void 0) { options = {}; }
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
- return this;
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
+ this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
@@ -107674,18 +107989,17 @@ var ts;
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
if (options === void 0) { options = {}; }
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
- return this;
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
+ this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
+ this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
var next = ts.findNextToken(node, node.parent, sourceFile);
@@ -107693,7 +108007,7 @@ var ts;
};
ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
- return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
+ this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
};
ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
if (options === void 0) { options = {}; }
@@ -107942,11 +108256,11 @@ var ts;
if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
- return this;
+ return;
}
var index = ts.indexOfNode(containingList, after);
if (index < 0) {
- return this;
+ return;
}
var end = after.getEnd();
if (index !== containingList.length - 1) {
@@ -108044,7 +108358,6 @@ var ts;
this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
}
}
- return this;
};
ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () {
var _this = this;
@@ -109261,9 +109574,8 @@ var ts;
cancellationToken.throwIfCancellationRequested();
inferTypeFromContext(reference, checker, usageContext);
}
- var isConstructor = declaration.kind === 157 /* Constructor */;
- var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
- return callContexts && declaration.parameters.map(function (parameter, parameterIndex) {
+ var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []);
+ return declaration.parameters.map(function (parameter, parameterIndex) {
var types = [];
var isRest = ts.isRestParameter(parameter);
var isOptional = false;
@@ -109283,7 +109595,8 @@ var ts;
}
}
if (ts.isIdentifier(parameter.name)) {
- types.push.apply(types, inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken));
+ var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken);
+ types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred));
}
var type = unifyFromContext(types, checker);
return {
@@ -109355,8 +109668,7 @@ var ts;
usageContext.isNumber = true;
break;
case 38 /* PlusToken */:
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
break;
// case SyntaxKind.ExclamationToken:
// no inferences here;
@@ -109418,8 +109730,7 @@ var ts;
usageContext.isString = true;
}
else {
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
}
break;
// AssignmentOperators
@@ -109484,8 +109795,7 @@ var ts;
}
function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) {
if (node === parent.argumentExpression) {
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
return;
}
else {
@@ -109500,18 +109810,48 @@ var ts;
}
}
}
+ function removeLowPriorityInferences(inferences, priorities) {
+ var toRemove = [];
+ for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
+ var i = inferences_2[_i];
+ for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
+ var _b = priorities_1[_a], high = _b.high, low = _b.low;
+ if (high(i)) {
+ ts.Debug.assert(!low(i));
+ toRemove.push(low);
+ }
+ }
+ }
+ return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); });
+ }
function unifyFromContext(inferences, checker, fallback) {
if (fallback === void 0) { fallback = checker.getAnyType(); }
if (!inferences.length)
return fallback;
- var hasNonVacuousType = inferences.some(function (i) { return !(i.flags & (1 /* Any */ | 16384 /* Void */)); });
- var hasNonVacuousNonAnonymousType = inferences.some(function (i) { return !(i.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(i) & 16 /* Anonymous */); });
- var anons = inferences.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; });
- var good = [];
- if (!hasNonVacuousNonAnonymousType && anons.length) {
+ // 1. string or number individually override string | number
+ // 2. non-any, non-void overrides any or void
+ // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types
+ var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]);
+ var priorities = [
+ {
+ high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); },
+ low: function (t) { return t === stringNumber; }
+ },
+ {
+ high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); },
+ low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); }
+ },
+ {
+ high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); },
+ low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); }
+ }
+ ];
+ var good = removeLowPriorityInferences(inferences, priorities);
+ var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; });
+ if (anons.length) {
+ good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); });
good.push(unifyAnonymousTypes(anons, checker));
}
- good.push.apply(good, inferences.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */) && !(hasNonVacuousType && i.flags & (1 /* Any */ | 16384 /* Void */)); }));
return checker.getWidenedType(checker.getUnionType(good));
}
InferFromReference.unifyFromContext = unifyFromContext;
@@ -109559,6 +109899,9 @@ var ts;
if (usageContext.isString) {
types.push(checker.getStringType());
}
+ if (usageContext.isNumberOrString) {
+ types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
+ }
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
@@ -109569,7 +109912,7 @@ var ts;
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
}
if (usageContext.numberIndexContext) {
- return [checker.createArrayType(recur(usageContext.numberIndexContext))];
+ types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
var members_6 = ts.createUnderscoreEscapedMap();
@@ -115311,7 +115654,7 @@ var ts;
// readonly modifier only existed in classLikeDeclaration
var constructor = ts.getFirstConstructorWithBody(container);
if (constructor) {
- updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
}
}
else {
@@ -115364,7 +115707,7 @@ var ts;
isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent,
- originalName: declaration.name,
+ originalName: declaration.name.text,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
@@ -115415,22 +115758,23 @@ var ts;
? changeTracker.insertNodeAfterComma(file, declaration, accessor)
: changeTracker.insertNodeAfter(file, declaration, accessor);
}
- function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) {
if (!constructor.body)
return;
- var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
- var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) {
- return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined;
- });
- ts.forEach(referenceEntries, function (entry) {
- var parent = entry.parent;
- var accessorName = ts.createIdentifier(fieldName.text);
- var node = ts.isBinaryExpression(parent)
- ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
- : ts.isPropertyAccessExpression(parent)
- ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
- : ts.Debug.fail("Unexpected write access token");
- changeTracker.replaceNode(file, parent, node);
+ constructor.body.forEachChild(function recur(node) {
+ if (ts.isElementAccessExpression(node) &&
+ node.expression.kind === 100 /* ThisKeyword */ &&
+ ts.isStringLiteral(node.argumentExpression) &&
+ node.argumentExpression.text === originalName &&
+ ts.isWriteAccess(node)) {
+ changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName));
+ }
+ if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) {
+ changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName));
+ }
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
+ node.forEachChild(recur);
+ }
});
}
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
@@ -117372,7 +117716,7 @@ var ts;
function shouldGetType(sourceFile, node, position) {
switch (node.kind) {
case 72 /* Identifier */:
- return !ts.isLabelName(node);
+ return !ts.isLabelName(node) && !ts.isTagName(node);
case 189 /* PropertyAccessExpression */:
case 148 /* QualifiedName */:
// Don't return quickInfo if inside the comment in `a/**/.b`
@@ -117954,7 +118298,7 @@ var ts;
function initializeNameTable(sourceFile) {
var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap();
sourceFile.forEachChild(function walk(node) {
- if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
+ if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
var text = ts.getEscapedTextOfIdentifierOrLiteral(node);
nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
}
@@ -118868,9 +119212,15 @@ var ts;
if ("directoryExists" in this.shimHost) {
this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
}
+ else {
+ this.directoryExists = undefined; // TODO: GH#18217
+ }
if ("realpath" in this.shimHost) {
this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217
}
+ else {
+ this.realpath = undefined; // TODO: GH#18217
+ }
}
CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) {
var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts
index 8cf2dcddc09..4c854caf6f8 100644
--- a/lib/typescriptServices.d.ts
+++ b/lib/typescriptServices.d.ts
@@ -1976,7 +1976,8 @@ declare namespace ts {
AllowEmptyTuple = 524288,
AllowUniqueESSymbolType = 1048576,
AllowEmptyIndexInfoType = 2097152,
- IgnoreErrors = 3112960,
+ AllowNodeModulesRelativePaths = 67108864,
+ IgnoreErrors = 70221824,
InObjectTypeLiteral = 4194304,
InTypeAlias = 8388608,
InInitialEntityName = 16777216,
@@ -3131,7 +3132,6 @@ declare namespace ts {
function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean;
function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner;
}
-/** Non-internal stuff goes here */
declare namespace ts {
function isExternalModuleNameRelative(moduleName: string): boolean;
function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray;
@@ -3478,6 +3478,7 @@ declare namespace ts {
type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail;
function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken;
function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail;
+ function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier;
function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken;
function isModifier(node: Node): node is Modifier;
function isEntityName(node: Node): node is EntityName;
@@ -4867,7 +4868,7 @@ declare namespace ts {
message: string;
position: number;
}
- class TextChange {
+ interface TextChange {
span: TextSpan;
newText: string;
}
diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js
index 9b296e619a2..43953811700 100644
--- a/lib/typescriptServices.js
+++ b/lib/typescriptServices.js
@@ -75,7 +75,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "3.2";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".1";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -3051,13 +3051,15 @@ var ts;
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
- NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors";
+ // Errors (cont.)
+ NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
+ /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
+ NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
// State
NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
- /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain";
})(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
// Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
var TypeFormatFlags;
@@ -5249,7 +5251,7 @@ var ts;
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
- An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."),
+ An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
@@ -5356,7 +5358,7 @@ var ts;
Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
- A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."),
+ A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."),
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
@@ -5439,7 +5441,7 @@ var ts;
_0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
- Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."),
+ Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
@@ -5470,7 +5472,7 @@ var ts;
Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
- Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."),
+ Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
@@ -5515,6 +5517,7 @@ var ts;
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
+ Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
@@ -5614,6 +5617,7 @@ var ts;
Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
+ The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
@@ -6009,6 +6013,7 @@ var ts;
Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
+ Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
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."),
@@ -6104,6 +6109,7 @@ var ts;
Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
+ Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
@@ -6172,6 +6178,9 @@ var ts;
Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"),
Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
+ Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
+ Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
+ Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
};
})(ts || (ts = {}));
var ts;
@@ -6401,11 +6410,28 @@ var ts;
}
ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
/* @internal */
- function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) {
+ function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) {
+ return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true);
+ }
+ ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits;
+ /* @internal */
+ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
if (line < 0 || line >= lineStarts.length) {
- ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ if (allowEdits) {
+ // Clamp line to nearest allowable value
+ line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
+ }
+ else {
+ ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ }
}
var res = lineStarts[line] + character;
+ if (allowEdits) {
+ // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
+ // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
+ // apply them to the computed position to improve accuracy
+ return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
+ }
if (line < lineStarts.length - 1) {
ts.Debug.assert(res < lineStarts[line + 1]);
}
@@ -8057,7 +8083,6 @@ var ts;
}
ts.createScanner = createScanner;
})(ts || (ts = {}));
-/** Non-internal stuff goes here */
var ts;
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -12342,6 +12367,31 @@ var ts;
return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
}
ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
+ function isTypeNodeKind(kind) {
+ return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
+ || kind === 120 /* AnyKeyword */
+ || kind === 143 /* UnknownKeyword */
+ || kind === 135 /* NumberKeyword */
+ || kind === 146 /* BigIntKeyword */
+ || kind === 136 /* ObjectKeyword */
+ || kind === 123 /* BooleanKeyword */
+ || kind === 138 /* StringKeyword */
+ || kind === 139 /* SymbolKeyword */
+ || kind === 100 /* ThisKeyword */
+ || kind === 106 /* VoidKeyword */
+ || kind === 141 /* UndefinedKeyword */
+ || kind === 96 /* NullKeyword */
+ || kind === 132 /* NeverKeyword */
+ || kind === 211 /* ExpressionWithTypeArguments */
+ || kind === 284 /* JSDocAllType */
+ || kind === 285 /* JSDocUnknownType */
+ || kind === 286 /* JSDocNullableType */
+ || kind === 287 /* JSDocNonNullableType */
+ || kind === 288 /* JSDocOptionalType */
+ || kind === 289 /* JSDocFunctionType */
+ || kind === 290 /* JSDocVariadicType */;
+ }
+ ts.isTypeNodeKind = isTypeNodeKind;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13810,6 +13860,10 @@ var ts;
|| kind === 17 /* TemplateTail */;
}
ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
+ function isImportOrExportSpecifier(node) {
+ return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
+ }
+ ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
function isStringTextContainingNode(node) {
return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
}
@@ -13978,37 +14032,13 @@ var ts;
}
ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
// Type
- function isTypeNodeKind(kind) {
- return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
- || kind === 120 /* AnyKeyword */
- || kind === 143 /* UnknownKeyword */
- || kind === 135 /* NumberKeyword */
- || kind === 146 /* BigIntKeyword */
- || kind === 136 /* ObjectKeyword */
- || kind === 123 /* BooleanKeyword */
- || kind === 138 /* StringKeyword */
- || kind === 139 /* SymbolKeyword */
- || kind === 100 /* ThisKeyword */
- || kind === 106 /* VoidKeyword */
- || kind === 141 /* UndefinedKeyword */
- || kind === 96 /* NullKeyword */
- || kind === 132 /* NeverKeyword */
- || kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
- }
/**
* Node test that determines whether a node is a valid type node.
* This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
* of a TypeNode.
*/
function isTypeNode(node) {
- return isTypeNodeKind(node.kind);
+ return ts.isTypeNodeKind(node.kind);
}
ts.isTypeNode = isTypeNode;
function isFunctionOrConstructorTypeNode(node) {
@@ -16529,53 +16559,46 @@ var ts;
return visitNodes(cbNode, cbNodes, node.tags);
case 299 /* JSDocParameterTag */:
case 305 /* JSDocPropertyTag */:
- if (node.isNameFirst) {
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.typeExpression);
- }
- else {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.name);
- }
- case 300 /* JSDocReturnTag */:
- return visitNode(cbNode, node.typeExpression);
- case 302 /* JSDocTypeTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ (node.isNameFirst
+ ? visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.typeExpression)
+ : visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.name));
case 295 /* JSDocAugmentsTag */:
- return visitNode(cbNode, node.class);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.class);
case 303 /* JSDocTemplateTag */:
- return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.constraint) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters);
case 304 /* JSDocTypedefTag */:
- if (node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */) {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.fullName);
- }
- else {
- return visitNode(cbNode, node.fullName) ||
- visitNode(cbNode, node.typeExpression);
- }
+ return visitNode(cbNode, node.tagName) ||
+ (node.typeExpression &&
+ node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ ? visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.fullName)
+ : visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression));
case 297 /* JSDocCallbackTag */:
- return visitNode(cbNode, node.fullName) ||
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
+ case 300 /* JSDocReturnTag */:
+ case 302 /* JSDocTypeTag */:
case 301 /* JSDocThisTag */:
- return visitNode(cbNode, node.typeExpression);
case 298 /* JSDocEnumTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.typeExpression);
case 293 /* JSDocSignature */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- ts.forEach(node.typeParameters, cbNode) ||
+ return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
case 292 /* JSDocTypeLiteral */:
- if (node.jsDocPropertyTags) {
- for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
- var tag = _a[_i];
- visitNode(cbNode, tag);
- }
- }
- return;
+ return ts.forEach(node.jsDocPropertyTags, cbNode);
+ case 294 /* JSDocTag */:
+ case 296 /* JSDocClassTag */:
+ return visitNode(cbNode, node.tagName);
case 308 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
@@ -23278,6 +23301,18 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "diagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_diagnostic_information
+ },
+ {
+ name: "extendedDiagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_verbose_diagnostic_information
+ },
];
/* @internal */
ts.optionDeclarations = ts.commonOptionsWithBuild.concat([
@@ -23741,18 +23776,6 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
},
- {
- name: "diagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_diagnostic_information
- },
- {
- name: "extendedDiagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_verbose_diagnostic_information
- },
{
name: "resolveJsonModule",
type: "boolean",
@@ -28223,6 +28246,7 @@ var ts;
}
}
function bindJSDocTypeAlias(node) {
+ node.tagName.parent = node;
if (node.fullName) {
setParentPointers(node, node.fullName);
}
@@ -29336,7 +29360,7 @@ var ts;
return true;
}
var node = symbol.valueDeclaration;
- if (ts.isCallExpression(node)) {
+ if (node && ts.isCallExpression(node)) {
return !!ts.getAssignedExpandoInitializer(node);
}
var init = !node ? undefined :
@@ -30908,17 +30932,7 @@ var ts;
var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
return parsed ? isImplementationOfOverload(parsed) : undefined;
},
- getImmediateAliasedSymbol: function (symbol) {
- ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
- var links = getSymbolLinks(symbol);
- if (!links.immediateTarget) {
- var node = getDeclarationOfAliasSymbol(symbol);
- if (!node)
- return ts.Debug.fail();
- links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
- }
- return links.immediateTarget;
- },
+ getImmediateAliasedSymbol: getImmediateAliasedSymbol,
getAliasedSymbol: resolveAlias,
getEmitResolver: getEmitResolver,
getExportsOfModule: getExportsOfModuleAsArray,
@@ -30948,6 +30962,7 @@ var ts;
getNumberType: function () { return numberType; },
createPromiseType: createPromiseType,
createArrayType: createArrayType,
+ getElementTypeOfArrayType: getElementTypeOfArrayType,
getBooleanType: function () { return booleanType; },
getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
@@ -31497,7 +31512,11 @@ var ts;
(source.flags | target.flags) & 67108864 /* Assignment */) {
ts.Debug.assert(source !== target);
if (!(target.flags & 33554432 /* Transient */)) {
- target = cloneSymbol(resolveSymbol(target));
+ var resolvedTarget = resolveSymbol(target);
+ if (resolvedTarget === unknownSymbol) {
+ return source;
+ }
+ target = cloneSymbol(resolvedTarget);
}
// Javascript static-property-assignment declarations always merge, even though they are also values
if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
@@ -32756,8 +32775,8 @@ var ts;
undefined;
return initializer || decl;
}
- function resolveExternalModuleName(location, moduleReferenceExpression) {
- return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
+ function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
+ return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0);
}
function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
if (isForAugmentation === void 0) { isForAugmentation = false; }
@@ -32785,7 +32804,7 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
- if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) {
+ if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
}
// merged symbol is module declaration symbol combined with all augmentations
@@ -33056,6 +33075,50 @@ var ts;
function getParentOfSymbol(symbol) {
return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
}
+ function getAlternativeContainingModules(symbol, enclosingDeclaration) {
+ var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
+ var id = "" + getNodeId(containingFile);
+ var links = getSymbolLinks(symbol);
+ var results;
+ if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
+ return results;
+ }
+ if (containingFile && containingFile.imports) {
+ // Try to make an import using an import already in the enclosing file, if possible
+ for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
+ var importRef = _a[_i];
+ if (ts.nodeIsSynthesized(importRef))
+ continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
+ var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
+ if (!resolvedModule)
+ continue;
+ var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, resolvedModule);
+ }
+ if (ts.length(results)) {
+ (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
+ return results;
+ }
+ }
+ if (links.extendedContainers) {
+ return links.extendedContainers;
+ }
+ // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
+ var otherFiles = host.getSourceFiles();
+ for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
+ var file = otherFiles_1[_b];
+ if (!ts.isExternalModule(file))
+ continue;
+ var sym = getSymbolOfNode(file);
+ var ref = getAliasForSymbolInContainer(sym, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, sym);
+ }
+ return links.extendedContainers = results || ts.emptyArray;
+ }
/**
* Attempts to find the symbol corresponding to the container a symbol is in - usually this
* is just its' `.parent`, but for locals, this value is `undefined`
@@ -33064,10 +33127,12 @@ var ts;
var container = getParentOfSymbol(symbol);
if (container) {
var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
+ var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
- return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope
+ return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
}
- return ts.append(additionalContainers, container);
+ var res = ts.append(additionalContainers, container);
+ return ts.concatenate(res, reexportContainers);
}
var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; });
if (!ts.length(candidates)) {
@@ -33506,7 +33571,7 @@ var ts;
}
function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
- var nodeFlags = 3112960 /* IgnoreErrors */;
+ var nodeFlags = 70221824 /* IgnoreErrors */;
if (flags & 2 /* UseOnlyExternalAliasing */) {
nodeFlags |= 128 /* UseOnlyExternalAliasing */;
}
@@ -33517,7 +33582,7 @@ var ts;
nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
}
if (flags & 16 /* DoNotIncludeSymbolChain */) {
- nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */;
+ nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
}
var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
@@ -33540,7 +33605,7 @@ var ts;
else {
sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */;
}
- var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
+ var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217
@@ -33551,7 +33616,7 @@ var ts;
if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
- var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
+ var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
if (typeNode === undefined)
return ts.Debug.fail("should always get typenode");
var options = { removeComments: true };
@@ -33602,7 +33667,7 @@ var ts;
enclosingDeclaration: enclosingDeclaration,
flags: flags || 0 /* None */,
// If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
- tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? {
+ tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
getSourceFiles: function () { return host.getSourceFiles(); },
getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); })
@@ -33855,11 +33920,7 @@ var ts;
return symbolToTypeNode(typeAlias, context, 67897832 /* Type */);
}
else {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
}
else {
@@ -33873,11 +33934,7 @@ var ts;
}
var depth = context.symbolDepth.get(id) || 0;
if (depth > 10) {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
context.symbolDepth.set(id, depth + 1);
context.visitedTypes.set(typeId, true);
@@ -34062,10 +34119,15 @@ var ts;
typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context));
}
if (resolvedType.stringIndexInfo) {
- var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ?
- createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) :
- resolvedType.stringIndexInfo;
- typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context));
+ var indexSignature = void 0;
+ if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
+ indexSignature.type = createElidedInformationPlaceholder(context);
+ }
+ else {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
+ }
+ typeElements.push(indexSignature);
}
if (resolvedType.numberIndexInfo) {
typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
@@ -34096,8 +34158,16 @@ var ts;
return typeElements.length ? typeElements : undefined;
}
}
+ function createElidedInformationPlaceholder(context) {
+ context.approximateLength += 3;
+ if (!(context.flags & 1 /* NoTruncation */)) {
+ return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
+ }
+ return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
function addPropertyToElementList(propertySymbol, context, typeElements) {
- var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ?
+ var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */);
+ var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
anyType : getTypeOfSymbol(propertySymbol);
var saveEnclosingDeclaration = context.enclosingDeclaration;
context.enclosingDeclaration = undefined;
@@ -34127,8 +34197,14 @@ var ts;
}
else {
var savedFlags = context.flags;
- context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0;
- var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
+ var propertyTypeNode = void 0;
+ if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
+ propertyTypeNode = createElidedInformationPlaceholder(context);
+ }
+ else {
+ propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
context.flags = savedFlags;
var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined;
if (modifiers) {
@@ -34314,7 +34390,7 @@ var ts;
// Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
var chain;
var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
- if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) {
+ if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
ts.Debug.assert(chain && chain.length > 0);
}
@@ -34325,13 +34401,22 @@ var ts;
/** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
function getSymbolChain(symbol, meaning, endOfChain) {
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
+ var parentSpecifiers;
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
// Go up and add our parent.
- var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
- if (ts.length(parents)) {
- for (var _i = 0, _a = parents; _i < _a.length; _i++) {
- var parent = _a[_i];
+ var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
+ if (ts.length(parents_1)) {
+ parentSpecifiers = parents_1.map(function (symbol) {
+ return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
+ ? getSpecifierForModuleSymbol(symbol, context)
+ : undefined;
+ });
+ var indices = parents_1.map(function (_, i) { return i; });
+ indices.sort(sortByBestName);
+ var sortedParents = indices.map(function (i) { return parents_1[i]; });
+ for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
+ var parent = sortedParents_1[_i];
var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
if (parentChain) {
accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
@@ -34354,6 +34439,24 @@ var ts;
}
return [symbol];
}
+ function sortByBestName(a, b) {
+ var specifierA = parentSpecifiers[a];
+ var specifierB = parentSpecifiers[b];
+ if (specifierA && specifierB) {
+ var isBRelative = ts.pathIsRelative(specifierB);
+ if (ts.pathIsRelative(specifierA) === isBRelative) {
+ // Both relative or both non-relative, sort by number of parts
+ return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
+ }
+ if (isBRelative) {
+ // A is non-relative, B is relative: prefer A
+ return -1;
+ }
+ // A is relative, B is non-relative: prefer B
+ return 1;
+ }
+ return 0;
+ }
}
}
function typeParametersToTypeParameterDeclarations(symbol, context) {
@@ -34442,6 +34545,14 @@ var ts;
var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
var specifier = getSpecifierForModuleSymbol(chain[0], context);
+ if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
+ // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
+ // since declaration files with these kinds of references are liable to fail when published :(
+ context.encounteredError = true;
+ if (context.tracker.reportLikelyUnsafeImportRequiredError) {
+ context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
+ }
+ }
var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
@@ -34578,7 +34689,7 @@ var ts;
if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
function typePredicateToStringWorker(writer) {
- var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
+ var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
var printer = ts.createPrinter({ removeComments: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
@@ -36003,7 +36114,7 @@ var ts;
return type.resolvedBaseTypes = ts.emptyArray;
}
if (!isValidBaseType(baseType)) {
- error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType));
+ error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType));
return type.resolvedBaseTypes = ts.emptyArray;
}
if (type === baseType || hasBaseType(baseType, type)) {
@@ -36059,7 +36170,7 @@ var ts;
}
}
else {
- error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface);
+ error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -39359,7 +39470,7 @@ var ts;
if (accessExpression) {
markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */);
if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) {
- error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop));
+ error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
return missingType;
}
if (cacheSymbol) {
@@ -41623,7 +41734,8 @@ var ts;
var bestMatchingType = findMatchingDiscriminantType(source, target) ||
findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
findBestTypeForObjectLiteral(source, target) ||
- findBestTypeForInvokable(source, target);
+ findBestTypeForInvokable(source, target) ||
+ findMostOverlappyType(source, target);
isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
}
return 0 /* False */;
@@ -41658,6 +41770,34 @@ var ts;
return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
}
}
+ function findMostOverlappyType(source, unionTarget) {
+ var bestMatch;
+ var matchingCount = 0;
+ for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
+ var target_1 = _a[_i];
+ var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]);
+ if (overlap.flags & 4194304 /* Index */) {
+ // perfect overlap of keys
+ bestMatch = target_1;
+ matchingCount = Infinity;
+ }
+ else if (overlap.flags & 1048576 /* Union */) {
+ // Some subset overlap if we have only string literals.
+ // If we have a union of index types, it seems likely that we
+ // needed to elaborate between two generic mapped types anyway.
+ var len = ts.length(overlap.types);
+ if (len >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = len;
+ }
+ }
+ else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = 1;
+ }
+ }
+ return bestMatch;
+ }
// Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
function findMatchingDiscriminantType(source, target) {
if (target.flags & 1048576 /* Union */) {
@@ -42760,12 +42900,8 @@ var ts;
return true;
}
// A source signature partially matches a target signature if the target signature has no fewer required
- // parameters and no more overall parameters than the source signature (where a signature with a rest
- // parameter is always considered to have more overall parameters than one without).
- var sourceRestCount = sourceHasRestParameter ? 1 : 0;
- var targetRestCount = targetHasRestParameter ? 1 : 0;
- if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount ||
- sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) {
+ // parameters
+ if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
return true;
}
return false;
@@ -42871,6 +43007,9 @@ var ts;
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
}
+ function getElementTypeOfArrayType(type) {
+ return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined;
+ }
function isArrayLikeType(type) {
// A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
// or if it is not the undefined or null type and if it is assignable to ReadonlyArray
@@ -43243,6 +43382,16 @@ var ts;
diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
break;
case 151 /* Parameter */:
+ var param = declaration;
+ if (ts.isIdentifier(param.name) &&
+ (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
+ param.parent.parameters.indexOf(param) > -1 &&
+ (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
+ param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
+ var newName = "arg" + param.parent.parameters.indexOf(param);
+ errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
+ return;
+ }
diagnostic = declaration.dotDotDotToken ?
noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage :
noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
@@ -45644,7 +45793,12 @@ var ts;
return errorType;
}
if (isReadonlySymbol(localOrExportSymbol)) {
- error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol));
+ if (localOrExportSymbol.flags & 3 /* Variable */) {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
+ }
+ else {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
+ }
return errorType;
}
}
@@ -47129,6 +47283,17 @@ var ts;
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
return createIndexInfo(unionType, /*isReadonly*/ false);
}
+ function getImmediateAliasedSymbol(symbol) {
+ ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
+ var links = getSymbolLinks(symbol);
+ if (!links.immediateTarget) {
+ var node = getDeclarationOfAliasSymbol(symbol);
+ if (!node)
+ return ts.Debug.fail();
+ links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
+ }
+ return links.immediateTarget;
+ }
function checkObjectLiteral(node, checkMode) {
var inDestructuringPattern = ts.isAssignmentTarget(node);
// Grammar checking
@@ -47596,16 +47761,31 @@ var ts;
function getJsxElementChildrenPropertyName(jsxNamespace) {
return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
- function getUninstantiatedJsxSignaturesOfType(elementType) {
+ function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
+ if (elementType.flags & 4 /* String */) {
+ return [anySignature];
+ }
+ else if (elementType.flags & 128 /* StringLiteral */) {
+ var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
+ if (!intrinsicType) {
+ error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
+ return ts.emptyArray;
+ }
+ else {
+ var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
+ return [fakeSignature];
+ }
+ }
+ var apparentElemType = getApparentType(elementType);
// Resolve the signatures, preferring constructor
- var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
+ var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
if (signatures.length === 0) {
// No construct signatures, try call signatures
- signatures = getSignaturesOfType(elementType, 0 /* Call */);
+ signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
}
- if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) {
+ if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
// If each member has some combination of new/call signatures; make a union signature list for those
- signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType));
+ signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
}
return signatures;
}
@@ -47978,7 +48158,7 @@ var ts;
checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop);
if (assignmentKind) {
if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) {
- error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right));
+ error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
return errorType;
}
}
@@ -49546,20 +49726,8 @@ var ts;
if (apparentType === errorType) {
return resolveErrorCall(node);
}
- if (exprTypes.flags & 128 /* StringLiteral */) {
- var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node);
- if (!intrinsicType) {
- error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements);
- return resolveUntypedCall(node);
- }
- else {
- var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes);
- return fakeSignature;
- }
- }
- var signatures = getUninstantiatedJsxSignaturesOfType(apparentType);
- if (exprTypes.flags & 4 /* String */ || isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
+ var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
+ if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
return resolveUntypedCall(node);
}
if (signatures.length === 0) {
@@ -51184,8 +51352,17 @@ var ts;
leftType;
case 59 /* EqualsToken */:
var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
- checkAssignmentDeclaration(declKind, right);
+ checkAssignmentDeclaration(declKind, rightType);
if (isAssignmentDeclaration(declKind)) {
+ if (!(rightType.flags & 524288 /* Object */) ||
+ declKind !== 2 /* ModuleExports */ &&
+ declKind !== 6 /* Prototype */ &&
+ !isEmptyObjectType(rightType) &&
+ !isFunctionObjectType(rightType) &&
+ !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
+ // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
+ checkAssignmentOperator(rightType);
+ }
return leftType;
}
else {
@@ -51200,10 +51377,9 @@ var ts;
default:
return ts.Debug.fail();
}
- function checkAssignmentDeclaration(kind, right) {
+ function checkAssignmentDeclaration(kind, rightType) {
if (kind === 2 /* ModuleExports */) {
- var rightType_1 = checkExpression(right, checkMode);
- for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
var prop = _a[_i];
var propType = getTypeOfSymbol(prop);
if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
@@ -53268,7 +53444,7 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
- if (produceDiagnostics) {
+ if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
@@ -53289,9 +53465,6 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 241 /* InterfaceDeclaration */:
- checkUnusedTypeParameters(node, addDiagnostic);
- break;
case 279 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
@@ -53308,7 +53481,7 @@ var ts;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- if (node.body) {
+ if (node.body) { // Don't report unused parameters in overloads
checkUnusedLocalsAndParameters(node, addDiagnostic);
}
checkUnusedTypeParameters(node, addDiagnostic);
@@ -53319,9 +53492,12 @@ var ts;
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 242 /* TypeAliasDeclaration */:
- case 176 /* InferType */:
+ case 241 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 176 /* InferType */:
+ checkUnusedInferTypeParameter(node, addDiagnostic);
+ break;
default:
ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
}
@@ -53336,77 +53512,73 @@ var ts;
return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
}
function checkUnusedClassMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
- var member = _a[_i];
- switch (member.kind) {
- case 156 /* MethodDeclaration */:
- case 154 /* PropertyDeclaration */:
- case 158 /* GetAccessor */:
- case 159 /* SetAccessor */:
- if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
- // Already would have reported an error on the getter.
- break;
- }
- var symbol = getSymbolOfNode(member);
- if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
- addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
- }
+ for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ switch (member.kind) {
+ case 156 /* MethodDeclaration */:
+ case 154 /* PropertyDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
+ // Already would have reported an error on the getter.
break;
- case 157 /* Constructor */:
- for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
- var parameter = _c[_b];
- if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
- addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
- }
+ }
+ var symbol = getSymbolOfNode(member);
+ if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
+ addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
+ }
+ break;
+ case 157 /* Constructor */:
+ for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
+ var parameter = _c[_b];
+ if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
+ addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
}
- break;
- case 162 /* IndexSignature */:
- case 217 /* SemicolonClassElement */:
- // Can't be private
- break;
- default:
- ts.Debug.fail();
- }
+ }
+ break;
+ case 162 /* IndexSignature */:
+ case 217 /* SemicolonClassElement */:
+ // Can't be private
+ break;
+ default:
+ ts.Debug.fail();
}
}
}
+ function checkUnusedInferTypeParameter(node, addDiagnostic) {
+ var typeParameter = node.typeParameter;
+ if (isTypeParameterUnused(typeParameter)) {
+ addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ }
+ }
function checkUnusedTypeParameters(node, addDiagnostic) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
- if (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node)
+ if (ts.last(getSymbolOfNode(node).declarations) !== node)
return;
- if (node.kind === 176 /* InferType */) {
- var typeParameter = node.typeParameter;
- if (isTypeParameterUnused(typeParameter)) {
- addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
+ var seenParentsWithEveryUnused = new ts.NodeSet();
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var typeParameter = typeParameters_2[_i];
+ if (!isTypeParameterUnused(typeParameter))
+ continue;
+ var name = ts.idText(typeParameter.name);
+ var parent = typeParameter.parent;
+ if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
+ if (seenParentsWithEveryUnused.tryAdd(parent)) {
+ var range = ts.isJSDocTemplateTag(parent)
+ // Whole @template tag
+ ? ts.rangeOfNode(parent)
+ // Include the `<>` in the error message
+ : ts.rangeOfTypeParameters(parent.typeParameters);
+ var only = typeParameters.length === 1;
+ var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
+ var arg0 = only ? name : undefined;
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
+ }
}
- }
- else {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
- if (!isTypeParameterUnused(typeParameter))
- continue;
- var name = ts.idText(typeParameter.name);
- var parent = typeParameter.parent;
- if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
- if (seenParentsWithEveryUnused.tryAdd(parent)) {
- var range = ts.isJSDocTemplateTag(parent)
- // Whole @template tag
- ? ts.rangeOfNode(parent)
- // Include the `<>` in the error message
- : ts.rangeOfTypeParameters(parent.typeParameters);
- var only = typeParameters.length === 1;
- var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
- var arg0 = only ? name : undefined;
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
- }
- }
- else {
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
- }
+ else {
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
}
}
}
@@ -53827,9 +53999,9 @@ var ts;
var nameText = ts.getTextOfPropertyName(name);
if (nameText) {
var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217
- markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
- if (parent.initializer && property) {
- checkPropertyAccessibility(parent, parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
+ if (property) {
+ markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
+ checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
}
}
}
@@ -54887,7 +55059,7 @@ var ts;
}
}
else {
- error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface);
+ error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -56493,7 +56665,10 @@ var ts;
}
if (isDeclarationNameOrImportPropertyName(node)) {
// This is a declaration, call getSymbolOfNode
- return getSymbolOfNode(parent);
+ var parentSymbol = getSymbolOfNode(parent);
+ return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
+ ? getImmediateAliasedSymbol(parentSymbol)
+ : parentSymbol;
}
else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
return getSymbolOfNode(parent.parent);
@@ -64701,7 +64876,7 @@ var ts;
};
function processMapping(mapping) {
var generatedPosition = generatedFile !== undefined
- ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
: -1;
var source;
var sourcePosition;
@@ -64710,7 +64885,7 @@ var ts;
var sourceFile = host.getSourceFileLike(sourceFilePath);
source = map.sources[mapping.sourceIndex];
sourcePosition = sourceFile !== undefined
- ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
: -1;
}
return {
@@ -79700,6 +79875,7 @@ var ts;
reportInaccessibleThisError: reportInaccessibleThisError,
reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
+ reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
moduleResolverHost: host,
trackReferencedAmbientModule: trackReferencedAmbientModule,
trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode
@@ -79788,6 +79964,11 @@ var ts;
context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
}
}
+ function reportLikelyUnsafeImportRequiredError(specifier) {
+ if (errorNameNode) {
+ context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
+ }
+ }
function transformRoot(node) {
if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
@@ -82775,7 +82956,7 @@ var ts;
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
function emitClassExpression(node) {
@@ -83513,7 +83694,7 @@ var ts;
}
function emitSpreadAssignment(node) {
if (node.expression) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
}
@@ -85483,7 +85664,7 @@ var ts;
var text;
try {
ts.performance.mark("beforeIORead");
- text = system.readFile(fileName, options.charset);
+ text = compilerHost.readFile(fileName);
ts.performance.mark("afterIORead");
ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
@@ -85509,7 +85690,12 @@ var ts;
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
- system.createDirectory(directoryPath);
+ if (compilerHost.createDirectory) {
+ compilerHost.createDirectory(directoryPath);
+ }
+ else {
+ system.createDirectory(directoryPath);
+ }
}
}
var outputFingerprints;
@@ -85561,7 +85747,7 @@ var ts;
}
var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
var realpath = system.realpath && (function (path) { return system.realpath(path); });
- return {
+ var compilerHost = {
getSourceFile: getSourceFile,
getDefaultLibLocation: getDefaultLibLocation,
getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
@@ -85577,10 +85763,113 @@ var ts;
getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return system.getDirectories(path); },
realpath: realpath,
- readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }
+ readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
+ createDirectory: function (d) { return system.createDirectory(d); }
};
+ return compilerHost;
}
ts.createCompilerHostWorker = createCompilerHostWorker;
+ /*@internal*/
+ function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) {
+ var originalReadFile = host.readFile;
+ var originalFileExists = host.fileExists;
+ var originalDirectoryExists = host.directoryExists;
+ var originalCreateDirectory = host.createDirectory;
+ var originalWriteFile = host.writeFile;
+ var originalGetSourceFile = host.getSourceFile;
+ var readFileCache = ts.createMap();
+ var fileExistsCache = ts.createMap();
+ var directoryExistsCache = ts.createMap();
+ var sourceFileCache = ts.createMap();
+ var readFileWithCache = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value || undefined;
+ return setReadFileCache(key, fileName);
+ };
+ var setReadFileCache = function (key, fileName) {
+ var newValue = originalReadFile.call(host, fileName);
+ readFileCache.set(key, newValue || false);
+ return newValue;
+ };
+ host.readFile = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value; // could be .d.ts from output
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return originalReadFile.call(host, fileName);
+ }
+ return setReadFileCache(key, fileName);
+ };
+ if (useCacheForSourceFile) {
+ host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
+ var key = toPath(fileName);
+ var value = sourceFileCache.get(key);
+ if (value)
+ return value;
+ var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile);
+ if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
+ sourceFileCache.set(key, sourceFile);
+ }
+ return sourceFile;
+ };
+ }
+ // fileExists for any kind of extension
+ host.fileExists = function (fileName) {
+ var key = toPath(fileName);
+ var value = fileExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalFileExists.call(host, fileName);
+ fileExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
+ var key = toPath(fileName);
+ fileExistsCache.delete(key);
+ var value = readFileCache.get(key);
+ if (value && value !== data) {
+ readFileCache.delete(key);
+ sourceFileCache.delete(key);
+ }
+ else if (useCacheForSourceFile) {
+ var sourceFile = sourceFileCache.get(key);
+ if (sourceFile && sourceFile.text !== data) {
+ sourceFileCache.delete(key);
+ }
+ }
+ originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
+ };
+ // directoryExists
+ if (originalDirectoryExists && originalCreateDirectory) {
+ host.directoryExists = function (directory) {
+ var key = toPath(directory);
+ var value = directoryExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalDirectoryExists.call(host, directory);
+ directoryExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.createDirectory = function (directory) {
+ var key = toPath(directory);
+ directoryExistsCache.delete(key);
+ originalCreateDirectory.call(host, directory);
+ };
+ }
+ return {
+ originalReadFile: originalReadFile,
+ originalFileExists: originalFileExists,
+ originalDirectoryExists: originalDirectoryExists,
+ originalCreateDirectory: originalCreateDirectory,
+ originalWriteFile: originalWriteFile,
+ originalGetSourceFile: originalGetSourceFile,
+ readFileWithCache: readFileWithCache
+ };
+ }
+ ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache;
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (ts.getEmitDeclarations(program.getCompilerOptions())) {
@@ -85967,6 +86256,7 @@ var ts;
// A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
var resolvedProjectReferences;
var projectReferenceRedirects;
+ var mapFromFileToProjectReferenceRedirects;
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2 /* Completely */) {
@@ -87325,15 +87615,20 @@ var ts;
* Get the referenced project if the file is input file from that reference project
*/
function getResolvedProjectReferenceToRedirect(fileName) {
- return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
- // not input file from the referenced project, ignore
- if (!referencedProject ||
- toPath(options.configFilePath) === referenceProjectPath ||
- !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) {
- return undefined;
- }
- return referencedProject;
- });
+ if (mapFromFileToProjectReferenceRedirects === undefined) {
+ mapFromFileToProjectReferenceRedirects = ts.createMap();
+ forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
+ // not input file from the referenced project, ignore
+ if (referencedProject &&
+ toPath(options.configFilePath) !== referenceProjectPath) {
+ referencedProject.commandLine.fileNames.forEach(function (f) {
+ return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
+ });
+ }
+ });
+ }
+ var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
+ return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
}
function forEachResolvedProjectReference(cb) {
return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
@@ -89696,6 +89991,7 @@ var ts;
}
return count;
}
+ moduleSpecifiers.countPathComponents = countPathComponents;
function usesJsExtensionOnImports(_a) {
var imports = _a.imports;
return ts.firstDefined(imports, function (_a) {
@@ -90903,6 +91199,7 @@ var ts;
var missingRoots = ts.createMap();
var globalDependencyGraph;
var writeFileName = function (s) { return host.trace && host.trace(s); };
+ var readFileWithCache = function (f) { return host.readFile(f); };
// Watch state
var diagnostics = createFileMap(toPath);
var projectPendingBuild = createFileMap(toPath);
@@ -91438,19 +91735,15 @@ var ts;
options: configFile.options,
configFileParsingDiagnostics: configFile.errors
};
+ if (host.beforeCreateProgram) {
+ host.beforeCreateProgram(options);
+ }
var program = ts.createProgram(programOptions);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
}
- // Don't emit .d.ts if there are decl file errors
- if (ts.getEmitDeclarations(program.getCompilerOptions())) {
- var declDiagnostics = program.getDeclarationDiagnostics();
- if (declDiagnostics.length) {
- return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
- }
- }
// Same as above but now for semantic diagnostics
var semanticDiagnostics = program.getSemanticDiagnostics();
if (semanticDiagnostics.length) {
@@ -91458,27 +91751,37 @@ var ts;
}
var newestDeclarationFileContentChangedTime = minimumDate;
var anyDtsChanged = false;
- var emitDiagnostics;
- var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); };
- ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) {
+ var declDiagnostics;
+ var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
+ var outputFiles = [];
+ ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); });
+ // Don't emit .d.ts if there are decl file errors
+ if (declDiagnostics) {
+ return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
+ }
+ // Actual Emit
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
var priorChangeTime;
- if (!anyDtsChanged && isDeclarationFile(fileName)) {
+ if (!anyDtsChanged && isDeclarationFile(name)) {
// Check for unchanged .d.ts files
- if (host.fileExists(fileName) && host.readFile(fileName) === content) {
- priorChangeTime = host.getModifiedTime(fileName);
+ if (host.fileExists(name) && readFileWithCache(name) === text) {
+ priorChangeTime = host.getModifiedTime(name);
}
else {
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
anyDtsChanged = true;
}
}
- host.writeFile(fileName, content, writeBom, onError, ts.emptyArray);
+ ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark);
if (priorChangeTime !== undefined) {
newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
- unchangedOutputs.setValue(fileName, priorChangeTime);
+ unchangedOutputs.setValue(name, priorChangeTime);
}
});
- if (emitDiagnostics) {
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
}
var status = {
@@ -91487,11 +91790,17 @@ var ts;
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
}
}
@@ -91558,11 +91867,16 @@ var ts;
if (options.watch) {
reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode);
}
+ // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api
+ // Override readFile for json files and output .d.ts to cache the text
+ var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache;
+ var savedReadFileWithCache = readFileWithCache;
+ readFileWithCache = newReadFileWithCache;
var graph = getGlobalDependencyGraph();
reportBuildQueue(graph);
var anyFailed = false;
- for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
- var next = _a[_i];
+ for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) {
+ var next = _b[_i];
var proj = parseConfigFile(next);
if (proj === undefined) {
reportParseConfigFileDiagnostic(next);
@@ -91604,6 +91918,13 @@ var ts;
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
+ host.readFile = originalReadFile;
+ host.fileExists = originalFileExists;
+ host.directoryExists = originalDirectoryExists;
+ host.createDirectory = originalCreateDirectory;
+ host.writeFile = originalWriteFile;
+ readFileWithCache = savedReadFileWithCache;
+ host.getSourceFile = originalGetSourceFile;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
function reportParseConfigFileDiagnostic(proj) {
@@ -92200,12 +92521,6 @@ var ts;
})(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {}));
/* @internal */
ts.emptyOptions = {};
- var TextChange = /** @class */ (function () {
- function TextChange() {
- }
- return TextChange;
- }());
- ts.TextChange = TextChange;
var HighlightSpanKind;
(function (HighlightSpanKind) {
HighlightSpanKind["none"] = "none";
@@ -92669,6 +92984,10 @@ var ts;
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
ts.isLabelName = isLabelName;
+ function isTagName(node) {
+ return ts.isJSDocTag(node.parent) && node.parent.tagName === node;
+ }
+ ts.isTagName = isTagName;
function isRightSideOfQualifiedName(node) {
return node.parent.kind === 148 /* QualifiedName */ && node.parent.right === node;
}
@@ -93559,6 +93878,7 @@ var ts;
ts.createTextChange = createTextChange;
ts.typeKeywords = [
120 /* AnyKeyword */,
+ 146 /* BigIntKeyword */,
123 /* BooleanKeyword */,
87 /* FalseKeyword */,
129 /* KeyOfKeyword */,
@@ -93992,9 +94312,7 @@ var ts;
}
ts.signatureToDisplayParts = signatureToDisplayParts;
function isImportOrExportSpecifierName(location) {
- return !!location.parent &&
- (location.parent.kind === 253 /* ImportSpecifier */ || location.parent.kind === 257 /* ExportSpecifier */) &&
- location.parent.propertyName === location;
+ return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location;
}
ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
/**
@@ -95416,26 +95734,21 @@ var ts;
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
*/
- function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) {
+ function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) {
// Make all paths absolute/normalized if they are not already
rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); });
// Determine the path to the directory containing the script relative to the root directory it is contained within
var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) {
- return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined;
+ return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined;
}); // TODO: GH#18217
// Now find a path for each potential directory that is to be merged with the one containing the script
- return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }).concat([scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
}
- function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensionOptions, compilerOptions, host, exclude) {
+ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) {
var basePath = compilerOptions.project || host.getCurrentDirectory();
var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
- var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase);
- var result = [];
- for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) {
- var baseDirectory = baseDirectories_1[_i];
- getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude, result);
- }
- return result;
+ var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
+ return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); });
}
/**
* Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
@@ -96666,7 +96979,8 @@ var ts;
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
isInSnippetScope = isSnippetScope(scopeNode);
- var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
+ var isTypeOnly = isTypeOnlyCompletion();
+ var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) {
@@ -96715,9 +97029,9 @@ var ts;
}
}
function filterGlobalCompletion(symbols) {
- var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
- var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
- if (isTypeOnlyCompletion)
+ var isTypeOnly = isTypeOnlyCompletion();
+ var allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
+ if (isTypeOnly)
keywordFilters = 6 /* TypeKeywords */;
ts.filterMutate(symbols, function (symbol) {
if (!ts.isSourceFile(location)) {
@@ -96733,7 +97047,7 @@ var ts;
if (allowTypes) {
// Its a type, but you can reach it by namespace.type as well
var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol);
- if (symbolAllowedAsType || isTypeOnlyCompletion) {
+ if (symbolAllowedAsType || isTypeOnly) {
return symbolAllowedAsType;
}
}
@@ -96742,6 +97056,9 @@ var ts;
return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */);
});
}
+ function isTypeOnlyCompletion() {
+ return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
+ }
function isContextTokenValueLocation(contextToken) {
return contextToken &&
contextToken.kind === 104 /* TypeOfKeyword */ &&
@@ -97127,6 +97444,7 @@ var ts;
if (contextToken) {
var parent = contextToken.parent;
switch (contextToken.kind) {
+ case 30 /* GreaterThanToken */: // End of a type argument list
case 29 /* LessThanSlashToken */:
case 42 /* SlashToken */:
case 72 /* Identifier */:
@@ -97135,6 +97453,11 @@ var ts;
case 267 /* JsxAttribute */:
case 269 /* JsxSpreadAttribute */:
if (parent && (parent.kind === 261 /* JsxSelfClosingElement */ || parent.kind === 262 /* JsxOpeningElement */)) {
+ if (contextToken.kind === 30 /* GreaterThanToken */) {
+ var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined);
+ if (!parent.typeArguments || (precedingToken && precedingToken.kind === 42 /* SlashToken */))
+ break;
+ }
return parent;
}
else if (parent.kind === 267 /* JsxAttribute */) {
@@ -98553,7 +98876,7 @@ var ts;
return undefined;
}
var lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
- return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false };
+ return { kind: 0 /* Import */, symbol: lhsSymbol };
}
else {
return exportInfo(symbol, getExportKindForDeclaration(exportNode));
@@ -98623,7 +98946,7 @@ var ts;
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
- return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
+ return { kind: 0 /* Import */, symbol: importedSymbol };
}
}
function exportInfo(symbol, kind) {
@@ -98668,18 +98991,16 @@ var ts;
var parent = node.parent;
switch (parent.kind) {
case 248 /* ImportEqualsDeclaration */:
- return parent.name === node && isExternalModuleImportEquals(parent)
- ? { isNamedImport: false }
- : undefined;
+ return parent.name === node && isExternalModuleImportEquals(parent);
case 253 /* ImportSpecifier */:
// For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
- return parent.propertyName ? undefined : { isNamedImport: true };
+ return !parent.propertyName;
case 250 /* ImportClause */:
case 251 /* NamespaceImport */:
ts.Debug.assert(parent.name === node);
- return { isNamedImport: false };
+ return true;
default:
- return undefined;
+ return false;
}
}
function getExportInfo(exportSymbol, exportKind, checker) {
@@ -98797,7 +99118,7 @@ var ts;
}
}
function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) {
- return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); });
+ return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); });
}
FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries;
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
@@ -98851,8 +99172,8 @@ var ts;
var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
return { displayParts: displayParts, kind: symbolKind };
}
- function toRenameLocation(entry, originalNode) {
- return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode));
+ function toRenameLocation(entry, originalNode, checker) {
+ return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker));
}
FindAllReferences.toRenameLocation = toRenameLocation;
function toReferenceEntry(entry) {
@@ -98881,25 +99202,27 @@ var ts;
return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName };
}
}
- function getPrefixAndSuffixText(entry, originalNode) {
+ function getPrefixAndSuffixText(entry, originalNode, checker) {
if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) {
var node = entry.node, kind = entry.kind;
var name = originalNode.text;
var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent);
if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) {
- if (kind === 3 /* SearchedLocalFoundProperty */) {
- return { prefixText: name + ": " };
- }
- else if (kind === 4 /* SearchedPropertyFoundLocal */) {
- return { suffixText: ": " + name };
- }
- else {
- return isShorthandAssignment
+ var prefixColon = { prefixText: name + ": " };
+ var suffixColon = { suffixText: ": " + name };
+ return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon
+ : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon
// In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol.
- ? { suffixText: ": " + name }
// For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol.
- : { prefixText: name + ": " };
- }
+ : isShorthandAssignment ? suffixColon : prefixColon;
+ }
+ else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
+ // If the original symbol was using this alias, just rename the alias.
+ var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
+ return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions;
+ }
+ else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
+ return originalNode === entry.node ? { prefixText: name + " as " } : { suffixText: " as " + name };
}
}
return ts.emptyOptions;
@@ -99154,13 +99477,18 @@ var ts;
return undefined;
}
/** Core find-all-references algorithm for a normal symbol. */
- function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
- symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
+ function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
+ var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol;
// Compute the meaning from the location and the symbol it references
var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
var result = [];
var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
- if (node && node.kind === 80 /* DefaultKeyword */) {
+ var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier);
+ if (exportSpecifier) {
+ // When renaming at an export specifier, rename the export and not the thing being exported.
+ getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true);
+ }
+ else if (node && node.kind === 80 /* DefaultKeyword */) {
addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
@@ -99198,15 +99526,11 @@ var ts;
}
}
/** Handle a few special cases relating to export/import specifiers. */
- function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) {
+ function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) {
var parent = node.parent;
- if (ts.isExportSpecifier(parent)) {
+ if (ts.isExportSpecifier(parent) && !isForRename) {
return getLocalSymbolForExportSpecifier(node, symbol, parent, checker);
}
- if (ts.isImportSpecifier(parent) && parent.propertyName === node) {
- // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import.
- return checker.getImmediateAliasedSymbol(symbol);
- }
// If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references.
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
@@ -99369,7 +99693,8 @@ var ts;
var indirectUser = indirectUsers_2[_b];
for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) {
var node = _d[_c];
- if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) {
+ // Import specifiers should be handled by importSearches
+ if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) {
cb(node);
}
}
@@ -99385,7 +99710,7 @@ var ts;
if (!ts.isIdentifier(singleRef))
return false;
// At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */);
+ return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */);
}
// Go to the symbol we imported from and find references for it.
function searchForImportedSymbol(symbol, state) {
@@ -99664,16 +99989,16 @@ var ts;
}
getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
}
- function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) {
+ function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) {
var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
var exportDeclaration = parent.parent;
var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
- if (!search.includes(localSymbol)) {
+ if (!alwaysGetReferences && !search.includes(localSymbol)) {
return;
}
if (!propertyName) {
// Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export)
- if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) {
+ if (!(state.options.isForRename && (name.escapedText === "default" /* Default */))) {
addRef();
}
}
@@ -99684,7 +100009,7 @@ var ts;
addRef();
}
if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) {
- addReference(name, referenceSymbol, state);
+ addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state);
}
}
else {
@@ -99693,15 +100018,14 @@ var ts;
}
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
- if (!(referenceLocation === propertyName && state.options.isForRename)) {
+ if (!state.options.isForRename || alwaysGetReferences) {
var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
- var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker);
- if (!exportInfo)
- return ts.Debug.fail();
- searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state);
+ var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
+ var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker));
+ searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
}
// At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
- if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) {
+ if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) {
var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
if (imported)
searchForImportedSymbol(imported, state);
@@ -99733,12 +100057,11 @@ var ts;
return;
var symbol = importOrExport.symbol;
if (importOrExport.kind === 0 /* Import */) {
- if (!state.options.isForRename || importOrExport.isNamedImport) {
+ if (!state.options.isForRename) {
searchForImportedSymbol(symbol, state);
}
}
else {
- // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching.
searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
}
}
@@ -103736,7 +104059,7 @@ var ts;
function getEnclosingDeclarationFromInvocation(invocation) {
return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
}
- var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
+ var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) {
var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
@@ -104902,16 +105225,11 @@ var ts;
this.options = options;
}
FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
- ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null");
- ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null");
- ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null");
- ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null");
- ts.Debug.assert(commonParent !== undefined, "commonParent is null");
- this.currentTokenSpan = currentRange;
- this.currentTokenParent = currentTokenParent;
- this.nextTokenSpan = nextRange;
- this.nextTokenParent = nextTokenParent;
- this.contextNode = commonParent;
+ this.currentTokenSpan = ts.Debug.assertDefined(currentRange);
+ this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent);
+ this.nextTokenSpan = ts.Debug.assertDefined(nextRange);
+ this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent);
+ this.contextNode = ts.Debug.assertDefined(commonParent);
// drop cached results
this.contextNodeAllOnSameLine = undefined;
this.nextNodeAllOnSameLine = undefined;
@@ -107637,7 +107955,6 @@ var ts;
};
ChangeTracker.prototype.deleteRange = function (sourceFile, range) {
this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range });
- return this;
};
ChangeTracker.prototype.delete = function (sourceFile, node) {
this.deletedNodes.push({ sourceFile: sourceFile, node: node });
@@ -107650,7 +107967,6 @@ var ts;
var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
- return this;
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
if (options === void 0) { options = {}; }
@@ -107661,11 +107977,10 @@ var ts;
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
if (options === void 0) { options = {}; }
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
- return this;
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
+ this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
@@ -107674,18 +107989,17 @@ var ts;
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
if (options === void 0) { options = {}; }
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
- return this;
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
+ this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
- return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
+ this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
var next = ts.findNextToken(node, node.parent, sourceFile);
@@ -107693,7 +108007,7 @@ var ts;
};
ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
- return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
+ this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
};
ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
if (options === void 0) { options = {}; }
@@ -107942,11 +108256,11 @@ var ts;
if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
- return this;
+ return;
}
var index = ts.indexOfNode(containingList, after);
if (index < 0) {
- return this;
+ return;
}
var end = after.getEnd();
if (index !== containingList.length - 1) {
@@ -108044,7 +108358,6 @@ var ts;
this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
}
}
- return this;
};
ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () {
var _this = this;
@@ -109261,9 +109574,8 @@ var ts;
cancellationToken.throwIfCancellationRequested();
inferTypeFromContext(reference, checker, usageContext);
}
- var isConstructor = declaration.kind === 157 /* Constructor */;
- var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
- return callContexts && declaration.parameters.map(function (parameter, parameterIndex) {
+ var callContexts = (usageContext.constructContexts || []).concat(usageContext.callContexts || []);
+ return declaration.parameters.map(function (parameter, parameterIndex) {
var types = [];
var isRest = ts.isRestParameter(parameter);
var isOptional = false;
@@ -109283,7 +109595,8 @@ var ts;
}
}
if (ts.isIdentifier(parameter.name)) {
- types.push.apply(types, inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken));
+ var inferred = inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken);
+ types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred));
}
var type = unifyFromContext(types, checker);
return {
@@ -109355,8 +109668,7 @@ var ts;
usageContext.isNumber = true;
break;
case 38 /* PlusToken */:
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
break;
// case SyntaxKind.ExclamationToken:
// no inferences here;
@@ -109418,8 +109730,7 @@ var ts;
usageContext.isString = true;
}
else {
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
}
break;
// AssignmentOperators
@@ -109484,8 +109795,7 @@ var ts;
}
function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) {
if (node === parent.argumentExpression) {
- usageContext.isNumber = true;
- usageContext.isString = true;
+ usageContext.isNumberOrString = true;
return;
}
else {
@@ -109500,18 +109810,48 @@ var ts;
}
}
}
+ function removeLowPriorityInferences(inferences, priorities) {
+ var toRemove = [];
+ for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
+ var i = inferences_2[_i];
+ for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
+ var _b = priorities_1[_a], high = _b.high, low = _b.low;
+ if (high(i)) {
+ ts.Debug.assert(!low(i));
+ toRemove.push(low);
+ }
+ }
+ }
+ return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); });
+ }
function unifyFromContext(inferences, checker, fallback) {
if (fallback === void 0) { fallback = checker.getAnyType(); }
if (!inferences.length)
return fallback;
- var hasNonVacuousType = inferences.some(function (i) { return !(i.flags & (1 /* Any */ | 16384 /* Void */)); });
- var hasNonVacuousNonAnonymousType = inferences.some(function (i) { return !(i.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(i) & 16 /* Anonymous */); });
- var anons = inferences.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; });
- var good = [];
- if (!hasNonVacuousNonAnonymousType && anons.length) {
+ // 1. string or number individually override string | number
+ // 2. non-any, non-void overrides any or void
+ // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types
+ var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]);
+ var priorities = [
+ {
+ high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); },
+ low: function (t) { return t === stringNumber; }
+ },
+ {
+ high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); },
+ low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); }
+ },
+ {
+ high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(t) & 16 /* Anonymous */); },
+ low: function (t) { return !!(checker.getObjectFlags(t) & 16 /* Anonymous */); }
+ }
+ ];
+ var good = removeLowPriorityInferences(inferences, priorities);
+ var anons = good.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; });
+ if (anons.length) {
+ good = good.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */); });
good.push(unifyAnonymousTypes(anons, checker));
}
- good.push.apply(good, inferences.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */) && !(hasNonVacuousType && i.flags & (1 /* Any */ | 16384 /* Void */)); }));
return checker.getWidenedType(checker.getUnionType(good));
}
InferFromReference.unifyFromContext = unifyFromContext;
@@ -109559,6 +109899,9 @@ var ts;
if (usageContext.isString) {
types.push(checker.getStringType());
}
+ if (usageContext.isNumberOrString) {
+ types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
+ }
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
@@ -109569,7 +109912,7 @@ var ts;
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
}
if (usageContext.numberIndexContext) {
- return [checker.createArrayType(recur(usageContext.numberIndexContext))];
+ types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
var members_6 = ts.createUnderscoreEscapedMap();
@@ -115311,7 +115654,7 @@ var ts;
// readonly modifier only existed in classLikeDeclaration
var constructor = ts.getFirstConstructorWithBody(container);
if (constructor) {
- updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
}
}
else {
@@ -115364,7 +115707,7 @@ var ts;
isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent,
- originalName: declaration.name,
+ originalName: declaration.name.text,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
@@ -115415,22 +115758,23 @@ var ts;
? changeTracker.insertNodeAfterComma(file, declaration, accessor)
: changeTracker.insertNodeAfter(file, declaration, accessor);
}
- function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) {
if (!constructor.body)
return;
- var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
- var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) {
- return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined;
- });
- ts.forEach(referenceEntries, function (entry) {
- var parent = entry.parent;
- var accessorName = ts.createIdentifier(fieldName.text);
- var node = ts.isBinaryExpression(parent)
- ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
- : ts.isPropertyAccessExpression(parent)
- ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
- : ts.Debug.fail("Unexpected write access token");
- changeTracker.replaceNode(file, parent, node);
+ constructor.body.forEachChild(function recur(node) {
+ if (ts.isElementAccessExpression(node) &&
+ node.expression.kind === 100 /* ThisKeyword */ &&
+ ts.isStringLiteral(node.argumentExpression) &&
+ node.argumentExpression.text === originalName &&
+ ts.isWriteAccess(node)) {
+ changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName));
+ }
+ if (ts.isPropertyAccessExpression(node) && node.expression.kind === 100 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) {
+ changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName));
+ }
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
+ node.forEachChild(recur);
+ }
});
}
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
@@ -117372,7 +117716,7 @@ var ts;
function shouldGetType(sourceFile, node, position) {
switch (node.kind) {
case 72 /* Identifier */:
- return !ts.isLabelName(node);
+ return !ts.isLabelName(node) && !ts.isTagName(node);
case 189 /* PropertyAccessExpression */:
case 148 /* QualifiedName */:
// Don't return quickInfo if inside the comment in `a/**/.b`
@@ -117954,7 +118298,7 @@ var ts;
function initializeNameTable(sourceFile) {
var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap();
sourceFile.forEachChild(function walk(node) {
- if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
+ if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
var text = ts.getEscapedTextOfIdentifierOrLiteral(node);
nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
}
@@ -118868,9 +119212,15 @@ var ts;
if ("directoryExists" in this.shimHost) {
this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
}
+ else {
+ this.directoryExists = undefined; // TODO: GH#18217
+ }
if ("realpath" in this.shimHost) {
this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217
}
+ else {
+ this.realpath = undefined; // TODO: GH#18217
+ }
}
CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) {
var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js
index f29014039b1..0110990b39d 100644
--- a/lib/typingsInstaller.js
+++ b/lib/typingsInstaller.js
@@ -88,7 +88,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "3.2";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".1";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -3064,13 +3064,15 @@ var ts;
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
- NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors";
+ // Errors (cont.)
+ NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
+ /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
+ NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
// State
NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
- /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain";
})(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
// Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
var TypeFormatFlags;
@@ -5262,7 +5264,7 @@ var ts;
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
- An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."),
+ An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."),
Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
@@ -5369,7 +5371,7 @@ var ts;
Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
- A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."),
+ A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."),
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
@@ -5452,7 +5454,7 @@ var ts;
_0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
- Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."),
+ Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),
Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
@@ -5483,7 +5485,7 @@ var ts;
Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
- Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."),
+ Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."),
The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
@@ -5528,6 +5530,7 @@ var ts;
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
+ Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
@@ -5627,6 +5630,7 @@ var ts;
Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"),
Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),
Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."),
+ The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),
Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
@@ -6022,6 +6026,7 @@ var ts;
Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),
Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, ts.DiagnosticCategory.Suggestion, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),
_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, ts.DiagnosticCategory.Suggestion, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),
+ Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, ts.DiagnosticCategory.Error, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"),
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."),
@@ -6117,6 +6122,7 @@ var ts;
Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
+ Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
@@ -6185,6 +6191,9 @@ var ts;
Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"),
Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"),
Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"),
+ Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
+ Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
+ Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
};
})(ts || (ts = {}));
var ts;
@@ -6414,11 +6423,28 @@ var ts;
}
ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
/* @internal */
- function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) {
+ function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) {
+ return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true);
+ }
+ ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits;
+ /* @internal */
+ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
if (line < 0 || line >= lineStarts.length) {
- ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ if (allowEdits) {
+ // Clamp line to nearest allowable value
+ line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
+ }
+ else {
+ ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
+ }
}
var res = lineStarts[line] + character;
+ if (allowEdits) {
+ // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
+ // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
+ // apply them to the computed position to improve accuracy
+ return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
+ }
if (line < lineStarts.length - 1) {
ts.Debug.assert(res < lineStarts[line + 1]);
}
@@ -8070,7 +8096,6 @@ var ts;
}
ts.createScanner = createScanner;
})(ts || (ts = {}));
-/** Non-internal stuff goes here */
var ts;
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -12355,6 +12380,31 @@ var ts;
return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
}
ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
+ function isTypeNodeKind(kind) {
+ return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
+ || kind === 120 /* AnyKeyword */
+ || kind === 143 /* UnknownKeyword */
+ || kind === 135 /* NumberKeyword */
+ || kind === 146 /* BigIntKeyword */
+ || kind === 136 /* ObjectKeyword */
+ || kind === 123 /* BooleanKeyword */
+ || kind === 138 /* StringKeyword */
+ || kind === 139 /* SymbolKeyword */
+ || kind === 100 /* ThisKeyword */
+ || kind === 106 /* VoidKeyword */
+ || kind === 141 /* UndefinedKeyword */
+ || kind === 96 /* NullKeyword */
+ || kind === 132 /* NeverKeyword */
+ || kind === 211 /* ExpressionWithTypeArguments */
+ || kind === 284 /* JSDocAllType */
+ || kind === 285 /* JSDocUnknownType */
+ || kind === 286 /* JSDocNullableType */
+ || kind === 287 /* JSDocNonNullableType */
+ || kind === 288 /* JSDocOptionalType */
+ || kind === 289 /* JSDocFunctionType */
+ || kind === 290 /* JSDocVariadicType */;
+ }
+ ts.isTypeNodeKind = isTypeNodeKind;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13823,6 +13873,10 @@ var ts;
|| kind === 17 /* TemplateTail */;
}
ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
+ function isImportOrExportSpecifier(node) {
+ return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
+ }
+ ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
function isStringTextContainingNode(node) {
return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
}
@@ -13991,37 +14045,13 @@ var ts;
}
ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
// Type
- function isTypeNodeKind(kind) {
- return (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */)
- || kind === 120 /* AnyKeyword */
- || kind === 143 /* UnknownKeyword */
- || kind === 135 /* NumberKeyword */
- || kind === 146 /* BigIntKeyword */
- || kind === 136 /* ObjectKeyword */
- || kind === 123 /* BooleanKeyword */
- || kind === 138 /* StringKeyword */
- || kind === 139 /* SymbolKeyword */
- || kind === 100 /* ThisKeyword */
- || kind === 106 /* VoidKeyword */
- || kind === 141 /* UndefinedKeyword */
- || kind === 96 /* NullKeyword */
- || kind === 132 /* NeverKeyword */
- || kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
- }
/**
* Node test that determines whether a node is a valid type node.
* This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
* of a TypeNode.
*/
function isTypeNode(node) {
- return isTypeNodeKind(node.kind);
+ return ts.isTypeNodeKind(node.kind);
}
ts.isTypeNode = isTypeNode;
function isFunctionOrConstructorTypeNode(node) {
@@ -16542,53 +16572,46 @@ var ts;
return visitNodes(cbNode, cbNodes, node.tags);
case 299 /* JSDocParameterTag */:
case 305 /* JSDocPropertyTag */:
- if (node.isNameFirst) {
- return visitNode(cbNode, node.name) ||
- visitNode(cbNode, node.typeExpression);
- }
- else {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.name);
- }
- case 300 /* JSDocReturnTag */:
- return visitNode(cbNode, node.typeExpression);
- case 302 /* JSDocTypeTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ (node.isNameFirst
+ ? visitNode(cbNode, node.name) ||
+ visitNode(cbNode, node.typeExpression)
+ : visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.name));
case 295 /* JSDocAugmentsTag */:
- return visitNode(cbNode, node.class);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.class);
case 303 /* JSDocTemplateTag */:
- return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.constraint) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters);
case 304 /* JSDocTypedefTag */:
- if (node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */) {
- return visitNode(cbNode, node.typeExpression) ||
- visitNode(cbNode, node.fullName);
- }
- else {
- return visitNode(cbNode, node.fullName) ||
- visitNode(cbNode, node.typeExpression);
- }
+ return visitNode(cbNode, node.tagName) ||
+ (node.typeExpression &&
+ node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ ? visitNode(cbNode, node.typeExpression) ||
+ visitNode(cbNode, node.fullName)
+ : visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression));
case 297 /* JSDocCallbackTag */:
- return visitNode(cbNode, node.fullName) ||
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
+ case 300 /* JSDocReturnTag */:
+ case 302 /* JSDocTypeTag */:
case 301 /* JSDocThisTag */:
- return visitNode(cbNode, node.typeExpression);
case 298 /* JSDocEnumTag */:
- return visitNode(cbNode, node.typeExpression);
+ return visitNode(cbNode, node.tagName) ||
+ visitNode(cbNode, node.typeExpression);
case 293 /* JSDocSignature */:
- return visitNodes(cbNode, cbNodes, node.decorators) ||
- visitNodes(cbNode, cbNodes, node.modifiers) ||
- ts.forEach(node.typeParameters, cbNode) ||
+ return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
case 292 /* JSDocTypeLiteral */:
- if (node.jsDocPropertyTags) {
- for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
- var tag = _a[_i];
- visitNode(cbNode, tag);
- }
- }
- return;
+ return ts.forEach(node.jsDocPropertyTags, cbNode);
+ case 294 /* JSDocTag */:
+ case 296 /* JSDocClassTag */:
+ return visitNode(cbNode, node.tagName);
case 308 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
@@ -23291,6 +23314,18 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "diagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_diagnostic_information
+ },
+ {
+ name: "extendedDiagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_verbose_diagnostic_information
+ },
];
/* @internal */
ts.optionDeclarations = ts.commonOptionsWithBuild.concat([
@@ -23754,18 +23789,6 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
},
- {
- name: "diagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_diagnostic_information
- },
- {
- name: "extendedDiagnostics",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Show_verbose_diagnostic_information
- },
{
name: "resolveJsonModule",
type: "boolean",
@@ -28236,6 +28259,7 @@ var ts;
}
}
function bindJSDocTypeAlias(node) {
+ node.tagName.parent = node;
if (node.fullName) {
setParentPointers(node, node.fullName);
}
@@ -29349,7 +29373,7 @@ var ts;
return true;
}
var node = symbol.valueDeclaration;
- if (ts.isCallExpression(node)) {
+ if (node && ts.isCallExpression(node)) {
return !!ts.getAssignedExpandoInitializer(node);
}
var init = !node ? undefined :
@@ -30921,17 +30945,7 @@ var ts;
var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
return parsed ? isImplementationOfOverload(parsed) : undefined;
},
- getImmediateAliasedSymbol: function (symbol) {
- ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
- var links = getSymbolLinks(symbol);
- if (!links.immediateTarget) {
- var node = getDeclarationOfAliasSymbol(symbol);
- if (!node)
- return ts.Debug.fail();
- links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
- }
- return links.immediateTarget;
- },
+ getImmediateAliasedSymbol: getImmediateAliasedSymbol,
getAliasedSymbol: resolveAlias,
getEmitResolver: getEmitResolver,
getExportsOfModule: getExportsOfModuleAsArray,
@@ -30961,6 +30975,7 @@ var ts;
getNumberType: function () { return numberType; },
createPromiseType: createPromiseType,
createArrayType: createArrayType,
+ getElementTypeOfArrayType: getElementTypeOfArrayType,
getBooleanType: function () { return booleanType; },
getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
@@ -31510,7 +31525,11 @@ var ts;
(source.flags | target.flags) & 67108864 /* Assignment */) {
ts.Debug.assert(source !== target);
if (!(target.flags & 33554432 /* Transient */)) {
- target = cloneSymbol(resolveSymbol(target));
+ var resolvedTarget = resolveSymbol(target);
+ if (resolvedTarget === unknownSymbol) {
+ return source;
+ }
+ target = cloneSymbol(resolvedTarget);
}
// Javascript static-property-assignment declarations always merge, even though they are also values
if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
@@ -32769,8 +32788,8 @@ var ts;
undefined;
return initializer || decl;
}
- function resolveExternalModuleName(location, moduleReferenceExpression) {
- return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
+ function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
+ return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0);
}
function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
if (isForAugmentation === void 0) { isForAugmentation = false; }
@@ -32798,7 +32817,7 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
- if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) {
+ if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
}
// merged symbol is module declaration symbol combined with all augmentations
@@ -33069,6 +33088,50 @@ var ts;
function getParentOfSymbol(symbol) {
return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
}
+ function getAlternativeContainingModules(symbol, enclosingDeclaration) {
+ var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
+ var id = "" + getNodeId(containingFile);
+ var links = getSymbolLinks(symbol);
+ var results;
+ if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
+ return results;
+ }
+ if (containingFile && containingFile.imports) {
+ // Try to make an import using an import already in the enclosing file, if possible
+ for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
+ var importRef = _a[_i];
+ if (ts.nodeIsSynthesized(importRef))
+ continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
+ var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
+ if (!resolvedModule)
+ continue;
+ var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, resolvedModule);
+ }
+ if (ts.length(results)) {
+ (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
+ return results;
+ }
+ }
+ if (links.extendedContainers) {
+ return links.extendedContainers;
+ }
+ // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
+ var otherFiles = host.getSourceFiles();
+ for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
+ var file = otherFiles_1[_b];
+ if (!ts.isExternalModule(file))
+ continue;
+ var sym = getSymbolOfNode(file);
+ var ref = getAliasForSymbolInContainer(sym, symbol);
+ if (!ref)
+ continue;
+ results = ts.append(results, sym);
+ }
+ return links.extendedContainers = results || ts.emptyArray;
+ }
/**
* Attempts to find the symbol corresponding to the container a symbol is in - usually this
* is just its' `.parent`, but for locals, this value is `undefined`
@@ -33077,10 +33140,12 @@ var ts;
var container = getParentOfSymbol(symbol);
if (container) {
var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
+ var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
- return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope
+ return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
}
- return ts.append(additionalContainers, container);
+ var res = ts.append(additionalContainers, container);
+ return ts.concatenate(res, reexportContainers);
}
var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; });
if (!ts.length(candidates)) {
@@ -33519,7 +33584,7 @@ var ts;
}
function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
- var nodeFlags = 3112960 /* IgnoreErrors */;
+ var nodeFlags = 70221824 /* IgnoreErrors */;
if (flags & 2 /* UseOnlyExternalAliasing */) {
nodeFlags |= 128 /* UseOnlyExternalAliasing */;
}
@@ -33530,7 +33595,7 @@ var ts;
nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
}
if (flags & 16 /* DoNotIncludeSymbolChain */) {
- nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */;
+ nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
}
var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
@@ -33553,7 +33618,7 @@ var ts;
else {
sigOutput = kind === 1 /* Construct */ ? 161 /* ConstructSignature */ : 160 /* CallSignature */;
}
- var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
+ var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonOmittingWriter(writer)); // TODO: GH#18217
@@ -33564,7 +33629,7 @@ var ts;
if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
- var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
+ var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
if (typeNode === undefined)
return ts.Debug.fail("should always get typenode");
var options = { removeComments: true };
@@ -33615,7 +33680,7 @@ var ts;
enclosingDeclaration: enclosingDeclaration,
flags: flags || 0 /* None */,
// If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
- tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? {
+ tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
getSourceFiles: function () { return host.getSourceFiles(); },
getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); })
@@ -33868,11 +33933,7 @@ var ts;
return symbolToTypeNode(typeAlias, context, 67897832 /* Type */);
}
else {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
}
else {
@@ -33886,11 +33947,7 @@ var ts;
}
var depth = context.symbolDepth.get(id) || 0;
if (depth > 10) {
- context.approximateLength += 3;
- if (!(context.flags & 1 /* NoTruncation */)) {
- return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
- }
- return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ return createElidedInformationPlaceholder(context);
}
context.symbolDepth.set(id, depth + 1);
context.visitedTypes.set(typeId, true);
@@ -34075,10 +34132,15 @@ var ts;
typeElements.push(signatureToSignatureDeclarationHelper(signature, 161 /* ConstructSignature */, context));
}
if (resolvedType.stringIndexInfo) {
- var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ?
- createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) :
- resolvedType.stringIndexInfo;
- typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context));
+ var indexSignature = void 0;
+ if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
+ indexSignature.type = createElidedInformationPlaceholder(context);
+ }
+ else {
+ indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
+ }
+ typeElements.push(indexSignature);
}
if (resolvedType.numberIndexInfo) {
typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
@@ -34109,8 +34171,16 @@ var ts;
return typeElements.length ? typeElements : undefined;
}
}
+ function createElidedInformationPlaceholder(context) {
+ context.approximateLength += 3;
+ if (!(context.flags & 1 /* NoTruncation */)) {
+ return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
+ }
+ return ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
function addPropertyToElementList(propertySymbol, context, typeElements) {
- var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ?
+ var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */);
+ var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
anyType : getTypeOfSymbol(propertySymbol);
var saveEnclosingDeclaration = context.enclosingDeclaration;
context.enclosingDeclaration = undefined;
@@ -34140,8 +34210,14 @@ var ts;
}
else {
var savedFlags = context.flags;
- context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0;
- var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
+ var propertyTypeNode = void 0;
+ if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
+ propertyTypeNode = createElidedInformationPlaceholder(context);
+ }
+ else {
+ propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ }
context.flags = savedFlags;
var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(133 /* ReadonlyKeyword */)] : undefined;
if (modifiers) {
@@ -34327,7 +34403,7 @@ var ts;
// Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
var chain;
var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
- if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) {
+ if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
ts.Debug.assert(chain && chain.length > 0);
}
@@ -34338,13 +34414,22 @@ var ts;
/** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
function getSymbolChain(symbol, meaning, endOfChain) {
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
+ var parentSpecifiers;
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
// Go up and add our parent.
- var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
- if (ts.length(parents)) {
- for (var _i = 0, _a = parents; _i < _a.length; _i++) {
- var parent = _a[_i];
+ var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
+ if (ts.length(parents_1)) {
+ parentSpecifiers = parents_1.map(function (symbol) {
+ return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
+ ? getSpecifierForModuleSymbol(symbol, context)
+ : undefined;
+ });
+ var indices = parents_1.map(function (_, i) { return i; });
+ indices.sort(sortByBestName);
+ var sortedParents = indices.map(function (i) { return parents_1[i]; });
+ for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
+ var parent = sortedParents_1[_i];
var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
if (parentChain) {
accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
@@ -34367,6 +34452,24 @@ var ts;
}
return [symbol];
}
+ function sortByBestName(a, b) {
+ var specifierA = parentSpecifiers[a];
+ var specifierB = parentSpecifiers[b];
+ if (specifierA && specifierB) {
+ var isBRelative = ts.pathIsRelative(specifierB);
+ if (ts.pathIsRelative(specifierA) === isBRelative) {
+ // Both relative or both non-relative, sort by number of parts
+ return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
+ }
+ if (isBRelative) {
+ // A is non-relative, B is relative: prefer A
+ return -1;
+ }
+ // A is relative, B is non-relative: prefer B
+ return 1;
+ }
+ return 0;
+ }
}
}
function typeParametersToTypeParameterDeclarations(symbol, context) {
@@ -34455,6 +34558,14 @@ var ts;
var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
var specifier = getSpecifierForModuleSymbol(chain[0], context);
+ if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
+ // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
+ // since declaration files with these kinds of references are liable to fail when published :(
+ context.encounteredError = true;
+ if (context.tracker.reportLikelyUnsafeImportRequiredError) {
+ context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
+ }
+ }
var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
@@ -34591,7 +34702,7 @@ var ts;
if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
function typePredicateToStringWorker(writer) {
- var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
+ var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
var printer = ts.createPrinter({ removeComments: true });
var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
@@ -36016,7 +36127,7 @@ var ts;
return type.resolvedBaseTypes = ts.emptyArray;
}
if (!isValidBaseType(baseType)) {
- error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType));
+ error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType));
return type.resolvedBaseTypes = ts.emptyArray;
}
if (type === baseType || hasBaseType(baseType, type)) {
@@ -36072,7 +36183,7 @@ var ts;
}
}
else {
- error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface);
+ error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -39372,7 +39483,7 @@ var ts;
if (accessExpression) {
markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 100 /* ThisKeyword */);
if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) {
- error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop));
+ error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
return missingType;
}
if (cacheSymbol) {
@@ -41636,7 +41747,8 @@ var ts;
var bestMatchingType = findMatchingDiscriminantType(source, target) ||
findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
findBestTypeForObjectLiteral(source, target) ||
- findBestTypeForInvokable(source, target);
+ findBestTypeForInvokable(source, target) ||
+ findMostOverlappyType(source, target);
isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
}
return 0 /* False */;
@@ -41671,6 +41783,34 @@ var ts;
return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
}
}
+ function findMostOverlappyType(source, unionTarget) {
+ var bestMatch;
+ var matchingCount = 0;
+ for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
+ var target_1 = _a[_i];
+ var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]);
+ if (overlap.flags & 4194304 /* Index */) {
+ // perfect overlap of keys
+ bestMatch = target_1;
+ matchingCount = Infinity;
+ }
+ else if (overlap.flags & 1048576 /* Union */) {
+ // Some subset overlap if we have only string literals.
+ // If we have a union of index types, it seems likely that we
+ // needed to elaborate between two generic mapped types anyway.
+ var len = ts.length(overlap.types);
+ if (len >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = len;
+ }
+ }
+ else if (!(overlap.flags & 131072 /* Never */) && 1 >= matchingCount) {
+ bestMatch = target_1;
+ matchingCount = 1;
+ }
+ }
+ return bestMatch;
+ }
// Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
function findMatchingDiscriminantType(source, target) {
if (target.flags & 1048576 /* Union */) {
@@ -42773,12 +42913,8 @@ var ts;
return true;
}
// A source signature partially matches a target signature if the target signature has no fewer required
- // parameters and no more overall parameters than the source signature (where a signature with a rest
- // parameter is always considered to have more overall parameters than one without).
- var sourceRestCount = sourceHasRestParameter ? 1 : 0;
- var targetRestCount = targetHasRestParameter ? 1 : 0;
- if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount ||
- sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) {
+ // parameters
+ if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
return true;
}
return false;
@@ -42884,6 +43020,9 @@ var ts;
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
}
+ function getElementTypeOfArrayType(type) {
+ return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined;
+ }
function isArrayLikeType(type) {
// A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
// or if it is not the undefined or null type and if it is assignable to ReadonlyArray
@@ -43256,6 +43395,16 @@ var ts;
diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
break;
case 151 /* Parameter */:
+ var param = declaration;
+ if (ts.isIdentifier(param.name) &&
+ (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
+ param.parent.parameters.indexOf(param) > -1 &&
+ (resolveName(param, param.name.escapedText, 67897832 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
+ param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
+ var newName = "arg" + param.parent.parameters.indexOf(param);
+ errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
+ return;
+ }
diagnostic = declaration.dotDotDotToken ?
noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage :
noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
@@ -45657,7 +45806,12 @@ var ts;
return errorType;
}
if (isReadonlySymbol(localOrExportSymbol)) {
- error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol));
+ if (localOrExportSymbol.flags & 3 /* Variable */) {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
+ }
+ else {
+ error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
+ }
return errorType;
}
}
@@ -47142,6 +47296,17 @@ var ts;
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
return createIndexInfo(unionType, /*isReadonly*/ false);
}
+ function getImmediateAliasedSymbol(symbol) {
+ ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
+ var links = getSymbolLinks(symbol);
+ if (!links.immediateTarget) {
+ var node = getDeclarationOfAliasSymbol(symbol);
+ if (!node)
+ return ts.Debug.fail();
+ links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
+ }
+ return links.immediateTarget;
+ }
function checkObjectLiteral(node, checkMode) {
var inDestructuringPattern = ts.isAssignmentTarget(node);
// Grammar checking
@@ -47609,16 +47774,31 @@ var ts;
function getJsxElementChildrenPropertyName(jsxNamespace) {
return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
- function getUninstantiatedJsxSignaturesOfType(elementType) {
+ function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
+ if (elementType.flags & 4 /* String */) {
+ return [anySignature];
+ }
+ else if (elementType.flags & 128 /* StringLiteral */) {
+ var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
+ if (!intrinsicType) {
+ error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
+ return ts.emptyArray;
+ }
+ else {
+ var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
+ return [fakeSignature];
+ }
+ }
+ var apparentElemType = getApparentType(elementType);
// Resolve the signatures, preferring constructor
- var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
+ var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
if (signatures.length === 0) {
// No construct signatures, try call signatures
- signatures = getSignaturesOfType(elementType, 0 /* Call */);
+ signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
}
- if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) {
+ if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
// If each member has some combination of new/call signatures; make a union signature list for those
- signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType));
+ signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
}
return signatures;
}
@@ -47991,7 +48171,7 @@ var ts;
checkPropertyAccessibility(node, left.kind === 98 /* SuperKeyword */, apparentType, prop);
if (assignmentKind) {
if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) {
- error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right));
+ error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
return errorType;
}
}
@@ -49559,20 +49739,8 @@ var ts;
if (apparentType === errorType) {
return resolveErrorCall(node);
}
- if (exprTypes.flags & 128 /* StringLiteral */) {
- var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node);
- if (!intrinsicType) {
- error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements);
- return resolveUntypedCall(node);
- }
- else {
- var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes);
- return fakeSignature;
- }
- }
- var signatures = getUninstantiatedJsxSignaturesOfType(apparentType);
- if (exprTypes.flags & 4 /* String */ || isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
+ var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
+ if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
return resolveUntypedCall(node);
}
if (signatures.length === 0) {
@@ -51197,8 +51365,17 @@ var ts;
leftType;
case 59 /* EqualsToken */:
var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
- checkAssignmentDeclaration(declKind, right);
+ checkAssignmentDeclaration(declKind, rightType);
if (isAssignmentDeclaration(declKind)) {
+ if (!(rightType.flags & 524288 /* Object */) ||
+ declKind !== 2 /* ModuleExports */ &&
+ declKind !== 6 /* Prototype */ &&
+ !isEmptyObjectType(rightType) &&
+ !isFunctionObjectType(rightType) &&
+ !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
+ // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
+ checkAssignmentOperator(rightType);
+ }
return leftType;
}
else {
@@ -51213,10 +51390,9 @@ var ts;
default:
return ts.Debug.fail();
}
- function checkAssignmentDeclaration(kind, right) {
+ function checkAssignmentDeclaration(kind, rightType) {
if (kind === 2 /* ModuleExports */) {
- var rightType_1 = checkExpression(right, checkMode);
- for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
var prop = _a[_i];
var propType = getTypeOfSymbol(prop);
if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
@@ -53281,7 +53457,7 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
- if (produceDiagnostics) {
+ if (produceDiagnostics && !(node.flags & 4194304 /* Ambient */)) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
@@ -53302,9 +53478,6 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 241 /* InterfaceDeclaration */:
- checkUnusedTypeParameters(node, addDiagnostic);
- break;
case 279 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
@@ -53321,7 +53494,7 @@ var ts;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- if (node.body) {
+ if (node.body) { // Don't report unused parameters in overloads
checkUnusedLocalsAndParameters(node, addDiagnostic);
}
checkUnusedTypeParameters(node, addDiagnostic);
@@ -53332,9 +53505,12 @@ var ts;
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 242 /* TypeAliasDeclaration */:
- case 176 /* InferType */:
+ case 241 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 176 /* InferType */:
+ checkUnusedInferTypeParameter(node, addDiagnostic);
+ break;
default:
ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
}
@@ -53349,77 +53525,73 @@ var ts;
return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
}
function checkUnusedClassMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
- var member = _a[_i];
- switch (member.kind) {
- case 156 /* MethodDeclaration */:
- case 154 /* PropertyDeclaration */:
- case 158 /* GetAccessor */:
- case 159 /* SetAccessor */:
- if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
- // Already would have reported an error on the getter.
- break;
- }
- var symbol = getSymbolOfNode(member);
- if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
- addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
- }
+ for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ switch (member.kind) {
+ case 156 /* MethodDeclaration */:
+ case 154 /* PropertyDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ if (member.kind === 159 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
+ // Already would have reported an error on the getter.
break;
- case 157 /* Constructor */:
- for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
- var parameter = _c[_b];
- if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
- addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
- }
+ }
+ var symbol = getSymbolOfNode(member);
+ if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
+ addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
+ }
+ break;
+ case 157 /* Constructor */:
+ for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
+ var parameter = _c[_b];
+ if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
+ addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
}
- break;
- case 162 /* IndexSignature */:
- case 217 /* SemicolonClassElement */:
- // Can't be private
- break;
- default:
- ts.Debug.fail();
- }
+ }
+ break;
+ case 162 /* IndexSignature */:
+ case 217 /* SemicolonClassElement */:
+ // Can't be private
+ break;
+ default:
+ ts.Debug.fail();
}
}
}
+ function checkUnusedInferTypeParameter(node, addDiagnostic) {
+ var typeParameter = node.typeParameter;
+ if (isTypeParameterUnused(typeParameter)) {
+ addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ }
+ }
function checkUnusedTypeParameters(node, addDiagnostic) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
- if (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node)
+ if (ts.last(getSymbolOfNode(node).declarations) !== node)
return;
- if (node.kind === 176 /* InferType */) {
- var typeParameter = node.typeParameter;
- if (isTypeParameterUnused(typeParameter)) {
- addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
+ var seenParentsWithEveryUnused = new ts.NodeSet();
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var typeParameter = typeParameters_2[_i];
+ if (!isTypeParameterUnused(typeParameter))
+ continue;
+ var name = ts.idText(typeParameter.name);
+ var parent = typeParameter.parent;
+ if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
+ if (seenParentsWithEveryUnused.tryAdd(parent)) {
+ var range = ts.isJSDocTemplateTag(parent)
+ // Whole @template tag
+ ? ts.rangeOfNode(parent)
+ // Include the `<>` in the error message
+ : ts.rangeOfTypeParameters(parent.typeParameters);
+ var only = typeParameters.length === 1;
+ var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
+ var arg0 = only ? name : undefined;
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
+ }
}
- }
- else {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
- if (!isTypeParameterUnused(typeParameter))
- continue;
- var name = ts.idText(typeParameter.name);
- var parent = typeParameter.parent;
- if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
- if (seenParentsWithEveryUnused.tryAdd(parent)) {
- var range = ts.isJSDocTemplateTag(parent)
- // Whole @template tag
- ? ts.rangeOfNode(parent)
- // Include the `<>` in the error message
- : ts.rangeOfTypeParameters(parent.typeParameters);
- var only = typeParameters.length === 1;
- var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
- var arg0 = only ? name : undefined;
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
- }
- }
- else {
- addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
- }
+ else {
+ addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
}
}
}
@@ -53840,9 +54012,9 @@ var ts;
var nameText = ts.getTextOfPropertyName(name);
if (nameText) {
var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217
- markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
- if (parent.initializer && property) {
- checkPropertyAccessibility(parent, parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
+ if (property) {
+ markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
+ checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 98 /* SuperKeyword */, parentType, property);
}
}
}
@@ -54900,7 +55072,7 @@ var ts;
}
}
else {
- error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface);
+ error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
}
}
}
@@ -56506,7 +56678,10 @@ var ts;
}
if (isDeclarationNameOrImportPropertyName(node)) {
// This is a declaration, call getSymbolOfNode
- return getSymbolOfNode(parent);
+ var parentSymbol = getSymbolOfNode(parent);
+ return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
+ ? getImmediateAliasedSymbol(parentSymbol)
+ : parentSymbol;
}
else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
return getSymbolOfNode(parent.parent);
@@ -64714,7 +64889,7 @@ var ts;
};
function processMapping(mapping) {
var generatedPosition = generatedFile !== undefined
- ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter)
: -1;
var source;
var sourcePosition;
@@ -64723,7 +64898,7 @@ var ts;
var sourceFile = host.getSourceFileLike(sourceFilePath);
source = map.sources[mapping.sourceIndex];
sourcePosition = sourceFile !== undefined
- ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
+ ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter)
: -1;
}
return {
@@ -79713,6 +79888,7 @@ var ts;
reportInaccessibleThisError: reportInaccessibleThisError,
reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
+ reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
moduleResolverHost: host,
trackReferencedAmbientModule: trackReferencedAmbientModule,
trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode
@@ -79801,6 +79977,11 @@ var ts;
context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
}
}
+ function reportLikelyUnsafeImportRequiredError(specifier) {
+ if (errorNameNode) {
+ context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
+ }
+ }
function transformRoot(node) {
if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
@@ -82788,7 +82969,7 @@ var ts;
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
function emitClassExpression(node) {
@@ -83526,7 +83707,7 @@ var ts;
}
function emitSpreadAssignment(node) {
if (node.expression) {
- writePunctuation("...");
+ emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
}
}
@@ -85496,7 +85677,7 @@ var ts;
var text;
try {
ts.performance.mark("beforeIORead");
- text = system.readFile(fileName, options.charset);
+ text = compilerHost.readFile(fileName);
ts.performance.mark("afterIORead");
ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
@@ -85522,7 +85703,12 @@ var ts;
if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = ts.getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
- system.createDirectory(directoryPath);
+ if (compilerHost.createDirectory) {
+ compilerHost.createDirectory(directoryPath);
+ }
+ else {
+ system.createDirectory(directoryPath);
+ }
}
}
var outputFingerprints;
@@ -85574,7 +85760,7 @@ var ts;
}
var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
var realpath = system.realpath && (function (path) { return system.realpath(path); });
- return {
+ var compilerHost = {
getSourceFile: getSourceFile,
getDefaultLibLocation: getDefaultLibLocation,
getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
@@ -85590,10 +85776,113 @@ var ts;
getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return system.getDirectories(path); },
realpath: realpath,
- readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }
+ readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
+ createDirectory: function (d) { return system.createDirectory(d); }
};
+ return compilerHost;
}
ts.createCompilerHostWorker = createCompilerHostWorker;
+ /*@internal*/
+ function changeCompilerHostToUseCache(host, toPath, useCacheForSourceFile) {
+ var originalReadFile = host.readFile;
+ var originalFileExists = host.fileExists;
+ var originalDirectoryExists = host.directoryExists;
+ var originalCreateDirectory = host.createDirectory;
+ var originalWriteFile = host.writeFile;
+ var originalGetSourceFile = host.getSourceFile;
+ var readFileCache = ts.createMap();
+ var fileExistsCache = ts.createMap();
+ var directoryExistsCache = ts.createMap();
+ var sourceFileCache = ts.createMap();
+ var readFileWithCache = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value || undefined;
+ return setReadFileCache(key, fileName);
+ };
+ var setReadFileCache = function (key, fileName) {
+ var newValue = originalReadFile.call(host, fileName);
+ readFileCache.set(key, newValue || false);
+ return newValue;
+ };
+ host.readFile = function (fileName) {
+ var key = toPath(fileName);
+ var value = readFileCache.get(key);
+ if (value !== undefined)
+ return value; // could be .d.ts from output
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return originalReadFile.call(host, fileName);
+ }
+ return setReadFileCache(key, fileName);
+ };
+ if (useCacheForSourceFile) {
+ host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
+ var key = toPath(fileName);
+ var value = sourceFileCache.get(key);
+ if (value)
+ return value;
+ var sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile);
+ if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
+ sourceFileCache.set(key, sourceFile);
+ }
+ return sourceFile;
+ };
+ }
+ // fileExists for any kind of extension
+ host.fileExists = function (fileName) {
+ var key = toPath(fileName);
+ var value = fileExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalFileExists.call(host, fileName);
+ fileExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
+ var key = toPath(fileName);
+ fileExistsCache.delete(key);
+ var value = readFileCache.get(key);
+ if (value && value !== data) {
+ readFileCache.delete(key);
+ sourceFileCache.delete(key);
+ }
+ else if (useCacheForSourceFile) {
+ var sourceFile = sourceFileCache.get(key);
+ if (sourceFile && sourceFile.text !== data) {
+ sourceFileCache.delete(key);
+ }
+ }
+ originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
+ };
+ // directoryExists
+ if (originalDirectoryExists && originalCreateDirectory) {
+ host.directoryExists = function (directory) {
+ var key = toPath(directory);
+ var value = directoryExistsCache.get(key);
+ if (value !== undefined)
+ return value;
+ var newValue = originalDirectoryExists.call(host, directory);
+ directoryExistsCache.set(key, !!newValue);
+ return newValue;
+ };
+ host.createDirectory = function (directory) {
+ var key = toPath(directory);
+ directoryExistsCache.delete(key);
+ originalCreateDirectory.call(host, directory);
+ };
+ }
+ return {
+ originalReadFile: originalReadFile,
+ originalFileExists: originalFileExists,
+ originalDirectoryExists: originalDirectoryExists,
+ originalCreateDirectory: originalCreateDirectory,
+ originalWriteFile: originalWriteFile,
+ originalGetSourceFile: originalGetSourceFile,
+ readFileWithCache: readFileWithCache
+ };
+ }
+ ts.changeCompilerHostToUseCache = changeCompilerHostToUseCache;
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (ts.getEmitDeclarations(program.getCompilerOptions())) {
@@ -85980,6 +86269,7 @@ var ts;
// A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
var resolvedProjectReferences;
var projectReferenceRedirects;
+ var mapFromFileToProjectReferenceRedirects;
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2 /* Completely */) {
@@ -87338,15 +87628,20 @@ var ts;
* Get the referenced project if the file is input file from that reference project
*/
function getResolvedProjectReferenceToRedirect(fileName) {
- return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
- // not input file from the referenced project, ignore
- if (!referencedProject ||
- toPath(options.configFilePath) === referenceProjectPath ||
- !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) {
- return undefined;
- }
- return referencedProject;
- });
+ if (mapFromFileToProjectReferenceRedirects === undefined) {
+ mapFromFileToProjectReferenceRedirects = ts.createMap();
+ forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
+ // not input file from the referenced project, ignore
+ if (referencedProject &&
+ toPath(options.configFilePath) !== referenceProjectPath) {
+ referencedProject.commandLine.fileNames.forEach(function (f) {
+ return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
+ });
+ }
+ });
+ }
+ var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
+ return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
}
function forEachResolvedProjectReference(cb) {
return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
@@ -89709,6 +90004,7 @@ var ts;
}
return count;
}
+ moduleSpecifiers.countPathComponents = countPathComponents;
function usesJsExtensionOnImports(_a) {
var imports = _a.imports;
return ts.firstDefined(imports, function (_a) {
@@ -90916,6 +91212,7 @@ var ts;
var missingRoots = ts.createMap();
var globalDependencyGraph;
var writeFileName = function (s) { return host.trace && host.trace(s); };
+ var readFileWithCache = function (f) { return host.readFile(f); };
// Watch state
var diagnostics = createFileMap(toPath);
var projectPendingBuild = createFileMap(toPath);
@@ -91451,19 +91748,15 @@ var ts;
options: configFile.options,
configFileParsingDiagnostics: configFile.errors
};
+ if (host.beforeCreateProgram) {
+ host.beforeCreateProgram(options);
+ }
var program = ts.createProgram(programOptions);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
}
- // Don't emit .d.ts if there are decl file errors
- if (ts.getEmitDeclarations(program.getCompilerOptions())) {
- var declDiagnostics = program.getDeclarationDiagnostics();
- if (declDiagnostics.length) {
- return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
- }
- }
// Same as above but now for semantic diagnostics
var semanticDiagnostics = program.getSemanticDiagnostics();
if (semanticDiagnostics.length) {
@@ -91471,27 +91764,37 @@ var ts;
}
var newestDeclarationFileContentChangedTime = minimumDate;
var anyDtsChanged = false;
- var emitDiagnostics;
- var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); };
- ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) {
+ var declDiagnostics;
+ var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
+ var outputFiles = [];
+ ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); });
+ // Don't emit .d.ts if there are decl file errors
+ if (declDiagnostics) {
+ return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
+ }
+ // Actual Emit
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
var priorChangeTime;
- if (!anyDtsChanged && isDeclarationFile(fileName)) {
+ if (!anyDtsChanged && isDeclarationFile(name)) {
// Check for unchanged .d.ts files
- if (host.fileExists(fileName) && host.readFile(fileName) === content) {
- priorChangeTime = host.getModifiedTime(fileName);
+ if (host.fileExists(name) && readFileWithCache(name) === text) {
+ priorChangeTime = host.getModifiedTime(name);
}
else {
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
anyDtsChanged = true;
}
}
- host.writeFile(fileName, content, writeBom, onError, ts.emptyArray);
+ ts.writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark);
if (priorChangeTime !== undefined) {
newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
- unchangedOutputs.setValue(fileName, priorChangeTime);
+ unchangedOutputs.setValue(name, priorChangeTime);
}
});
- if (emitDiagnostics) {
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
}
var status = {
@@ -91500,11 +91803,17 @@ var ts;
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
+ if (host.afterProgramEmitAndDiagnostics) {
+ host.afterProgramEmitAndDiagnostics(program);
+ }
return resultFlags;
}
}
@@ -91571,11 +91880,16 @@ var ts;
if (options.watch) {
reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode);
}
+ // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api
+ // Override readFile for json files and output .d.ts to cache the text
+ var _a = ts.changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, originalGetSourceFile = _a.originalGetSourceFile, newReadFileWithCache = _a.readFileWithCache;
+ var savedReadFileWithCache = readFileWithCache;
+ readFileWithCache = newReadFileWithCache;
var graph = getGlobalDependencyGraph();
reportBuildQueue(graph);
var anyFailed = false;
- for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
- var next = _a[_i];
+ for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) {
+ var next = _b[_i];
var proj = parseConfigFile(next);
if (proj === undefined) {
reportParseConfigFileDiagnostic(next);
@@ -91617,6 +91931,13 @@ var ts;
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
+ host.readFile = originalReadFile;
+ host.fileExists = originalFileExists;
+ host.directoryExists = originalDirectoryExists;
+ host.createDirectory = originalCreateDirectory;
+ host.writeFile = originalWriteFile;
+ readFileWithCache = savedReadFileWithCache;
+ host.getSourceFile = originalGetSourceFile;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
function reportParseConfigFileDiagnostic(proj) {