From ff0422091fb9de5f6d702ae4ab6fe26f806a1ab5 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 2 Mar 2020 15:15:41 -0800 Subject: [PATCH] Update LKG (#37175) * Update LKG * Remove unneeded check (handled by top of function) --- lib/de/diagnosticMessages.generated.json | 5 +- lib/ko/diagnosticMessages.generated.json | 6 +- lib/pl/diagnosticMessages.generated.json | 6 +- lib/pt-br/diagnosticMessages.generated.json | 6 +- lib/ru/diagnosticMessages.generated.json | 5 +- lib/tsc.js | 222 +++++--- lib/tsserver.js | 567 +++++++++++++------- lib/tsserverlibrary.js | 565 ++++++++++++------- lib/typescript.js | 561 ++++++++++++------- lib/typescriptServices.js | 561 ++++++++++++------- lib/typingsInstaller.js | 267 +++++---- lib/zh-cn/diagnosticMessages.generated.json | 6 +- src/compiler/utilities.ts | 2 +- 13 files changed, 1813 insertions(+), 966 deletions(-) diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 86ddd352508..c711b220b1f 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -761,7 +761,8 @@ "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Nur auf öffentliche und geschützte Methoden der Basisklasse kann über das Schlüsselwort \"super\" zugegriffen werden.", "Operator_0_cannot_be_applied_to_type_1_2736": "Der Operator \"{0}\" kann nicht auf den Typ \"{1}\" angewendet werden.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Der Operator \"{0}\" darf nicht auf die Typen \"{1}\" und \"{2}\" angewendet werden.", - "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Die Option \"{0}\" kann nur in der Datei \"tsconfig.json\" angegeben werden.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "Die Option \"{0}\" kann nur in der Datei \"tsconfig.json\" angegeben oder in der Befehlszeile auf FALSE oder NULL festgelegt werden.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "Die Option \"{0}\" kann nur in der Datei \"tsconfig.json\" angegeben oder in der Befehlszeile auf NULL festgelegt werden.", "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Die Option \"{0}\" kann nur verwendet werden, wenn die Option \"-inlineSourceMap\" oder \"-sourceMap\" angegeben wird.", "Option_0_cannot_be_specified_when_option_target_is_ES3_5048": "Die Option \"{0}\" kann nicht angegeben werden, wenn die Option \"target\" den Wert \"ES3\" aufweist.", "Option_0_cannot_be_specified_with_option_1_5053": "Die Option \"{0}\" darf nicht zusammen mit der Option \"{1}\" angegeben werden.", @@ -1035,7 +1036,7 @@ "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Der Symbol-Verweis verweist nicht auf das globale Symbolkonstruktorobjekt.", "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228": "Rufen Sie Rückrufe synchron auf, und aktualisieren Sie den Status von Verzeichnisüberwachungen auf Plattformen, die nativ keine rekursive Überwachung unterstützen.", "Syntax_Colon_0_6023": "Syntax: {0}", - "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'.", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "Das Tag \"{0}\" erwartet mindestens {1} Argumente, von der JSX-Factory \"{2}\" werden aber höchstens {3} bereitgestellt.", "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "Mit Tags versehene Vorlagenausdrücke sind in einer optionalen Kette nicht zulässig.", "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "Der Modifizierer \"{0}\" kann nur in TypeScript-Dateien verwendet werden.", "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Der Operator \"{0}\" darf nicht den Typ \"symbol\" angewendet werden.", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index 39ebe4b8f2a..9b24b74fa25 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -758,10 +758,12 @@ "Only_amd_and_system_modules_are_supported_alongside_0_6082": "'amd' 및 'system' 모듈만 --{0}과(와) 함께 사용할 수 있습니다.", "Only_emit_d_ts_declaration_files_6014": "'.d.ts' 선언 파일만 내보냅니다.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "선택적 형식 인수가 포함된 식별자/정규화된 이름만 현재 클래스 'extends' 절에서 지원됩니다.", + "Only_named_exports_may_use_export_type_1383": "Only named exports may use 'export type'.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "기본 클래스의 공용 및 보호된 메서드만 'super' 키워드를 통해 액세스할 수 있습니다.", "Operator_0_cannot_be_applied_to_type_1_2736": "'{0}' 연산자는 '{1}' 형식에 적용할 수 없습니다.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "'{0}' 연산자를 '{1}' 및 '{2}' 형식에 적용할 수 없습니다.", - "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "'{0}' 옵션은 'tsconfig.json' 파일에만 지정할 수 있습니다.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "'{0}' 옵션은 'tsconfig. json' 파일에만 지정하거나 명령줄에서 'false' 또는 'null'로 설정할 수 있습니다.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "'{0}' 옵션은 'tsconfig. json' 파일에만 지정하거나 명령줄에서 'null'로 설정할 수 있습니다.", "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "'{0}' 옵션은 '--inlineSourceMap' 옵션 또는 '--sourceMap' 옵션이 제공되는 경우에만 사용할 수 있습니다.", "Option_0_cannot_be_specified_when_option_target_is_ES3_5048": "'target' 옵션이 'ES3'인 경우 '{0}' 옵션을 지정할 수 없습니다.", "Option_0_cannot_be_specified_with_option_1_5053": "'{0}' 옵션은 '{1}' 옵션과 함께 지정할 수 없습니다.", @@ -1035,6 +1037,7 @@ "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "'기호' 참조에서 전역 기호 생성자 개체를 참조하지 않습니다.", "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228": "비동기적으로 콜백을 호출하며 기본적으로 재귀 조사를 지원하지 않는 플랫폼에서 디렉터리 감시자의 상태를 업데이트합니다.", "Syntax_Colon_0_6023": "구문: {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "'{0}' 태그는 '{1}'개 이상의 인수가 필요한데 JSX 팩터리 '{2}'이(가) 최대 '{3}'개를 제공합니다.", "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "태그가 지정된 템플릿 식은 선택적 체인에서 사용할 수 없습니다.", "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "'{0}' 한정자는 TypeScript 파일에서만 사용할 수 있습니다.", "The_0_operator_cannot_be_applied_to_type_symbol_2469": "'{0}' 연산자는 'symbol' 유형에 적용될 수 없습니다.", @@ -1179,6 +1182,7 @@ "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "계산된 속성 값의 형식은 '{1}' 형식에 할당할 수 없는 '{0}'입니다.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*'의 반복되는 요소 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Type of property '{0}' circularly references itself in mapped type '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "비동기 생성기에 있는 'yield' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "형식이 이 가져오기에서 시작됩니다. 네임스페이스 스타일 가져오기는 호출하거나 생성할 수 없으며, 런타임에 오류를 초래합니다. 여기서는 대신 기본 가져오기 또는 가져오기 필요를 사용하는 것이 좋습니다.", "Type_parameter_0_has_a_circular_constraint_2313": "형식 매개 변수 '{0}'에 순환 제약 조건이 있습니다.", diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 2aa9ca7b872..d588d7c93c4 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -758,10 +758,12 @@ "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Tylko moduły „amd” i „system” są obsługiwane razem z parametrem --{0}.", "Only_emit_d_ts_declaration_files_6014": "Emituj tylko pliki deklaracji „d.ts”.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Klauzula „extends” klasy obsługuje obecnie tylko identyfikatory/nazwy kwalifikowane z opcjonalnymi argumentami typu.", + "Only_named_exports_may_use_export_type_1383": "Only named exports may use 'export type'.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Tylko publiczne i chronione metody klasy bazowej są dostępne przy użyciu słowa kluczowego „super”.", "Operator_0_cannot_be_applied_to_type_1_2736": "Nie można zastosować operatora „{0}” do typu „{1}”.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Nie można zastosować operatora „{0}” do typów „{1}” i „{2}”.", - "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Opcję „{0}” można określić jedynie w pliku „tsconfig.json”.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "Opcję „{0}” można określić tylko w pliku „tsconfig.json” albo ustawić na wartość „false” lub „null” w wierszu polecenia.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "Opcję „{0}” można określić tylko w pliku „tsconfig.json” albo ustawić na wartość „null” w wierszu polecenia.", "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Opcja „{0}” może być używana tylko w przypadku podania opcji „--inlineSourceMap” lub „--sourceMap”.", "Option_0_cannot_be_specified_when_option_target_is_ES3_5048": "Nie można określić opcji „{0}”, jeśli opcja „target” ma wartość „ES3”.", "Option_0_cannot_be_specified_with_option_1_5053": "Opcji „{0}” nie można określić razem z opcją „{1}”.", @@ -1035,6 +1037,7 @@ "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Odwołanie do elementu „Symbol” nie zawiera odwołania do globalnego obiektu konstruktora symboli.", "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228": "Synchronicznie wywołaj wywołania zwrotne i zaktualizuj stan obserwatorów katalogów na platformach, które nie obsługują natywnego obserwowania rekursywnego.", "Syntax_Colon_0_6023": "Składnia: {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "Tag „{0}” oczekuje co najmniej „{1}” argumentów, ale fabryka JSX „{2}” dostarcza maksymalnie „{3}”.", "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "Oznakowane wyrażenia szablonu nie są dozwolone w opcjonalnym łańcuchu.", "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "Modyfikatora „{0}” można używać tylko w plikach TypeScript.", "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Nie można zastosować operatora „{0}” do typu „symbol”.", @@ -1179,6 +1182,7 @@ "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Typ operandu „await” musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Typ wartości właściwości obliczanej to „{0}”, którego nie można przypisać do typu „{1}”.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterowanych elementów operandu „yield*” musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Type of property '{0}' circularly references itself in mapped type '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu „yield” w generatorze asynchronicznym musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Typ pochodzi z tego importu. Nie można wywołać ani skonstruować importu w stylu przestrzeni nazw, co spowoduje wystąpienie błędu w czasie wykonywania. Zamiast tego rozważ użycie importu domyślnego lub funkcji require importu.", "Type_parameter_0_has_a_circular_constraint_2313": "Parametr typu „{0}” zawiera ograniczenie cykliczne.", diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index a3f9381cfc1..01056f134ed 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -758,10 +758,12 @@ "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Há suporte somente aos módulos 'amd' e 'system' ao lado de --{0}.", "Only_emit_d_ts_declaration_files_6014": "Emita somente arquivos de declaração '.d.ts'.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Somente os identificadores/nomes qualificados com argumentos de tipo opcionais tem suporte atualmente nas cláusulas de classe 'extends'.", + "Only_named_exports_may_use_export_type_1383": "Only named exports may use 'export type'.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Somente métodos protegidos e públicos da classe base são acessíveis pela palavra-chave 'super'.", "Operator_0_cannot_be_applied_to_type_1_2736": "O operador '{0}' não pode ser aplicado ao tipo '{1}'.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "O operador '{0}' não pode ser aplicado aos tipos '{1}' e '{2}'.", - "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "A opção '{0}' só pode ser especificada no arquivo 'tsconfig.json'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "A opção '{0}' somente pode ser especificada no arquivo 'tsconfig.json' ou definida como 'false' ou 'null' na linha de comando.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "A opção '{0}' somente pode ser especificada no arquivo 'tsconfig.json' ou definida como 'null' na linha de comando.", "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "A opção '{0} só pode ser usada quando qualquer uma das opções '--inlineSourceMap' ou '--sourceMap' é fornecida.", "Option_0_cannot_be_specified_when_option_target_is_ES3_5048": "A opção '{0}' não pode ser especificada quando a opção 'target' é 'ES3'.", "Option_0_cannot_be_specified_with_option_1_5053": "A opção '{0}' não pode ser especificada com a opção '{1}'.", @@ -1035,7 +1037,7 @@ "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "A referência 'symbol' não se refere ao objeto global do construtor Symbol.", "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228": "Chame sincronicamente retornos de chamadas e atualize o estado de observadores de diretório em plataformas que não têm suporte à observação recursiva nativamente.", "Syntax_Colon_0_6023": "Sintaxe: {0}", - "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'.", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "A tag '{0}' espera no mínimo os argumentos '{1}', mas o alocador JSX '{2}' fornece no máximo '{3}'.", "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "Expressões de modelo marcado não são permitidas em uma cadeia opcional.", "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "O modificador '{0}' só pode ser usado em arquivos TypeScript.", "The_0_operator_cannot_be_applied_to_type_symbol_2469": "O operador '{0}' não pode ser aplicado ao tipo 'symbol'.", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index a5055000a1e..6c351ab2a0c 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -758,10 +758,12 @@ "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Только модули amd и system поддерживаются вместе с --{0}.", "Only_emit_d_ts_declaration_files_6014": "Порождаются только файлы объявлений \".d.ts\".", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "В предложениях extends класса сейчас поддерживаются только идентификаторы или полные имена с необязательными аргументами типа.", + "Only_named_exports_may_use_export_type_1383": "Only named exports may use 'export type'.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Через ключевое слово super доступны только общие и защищенные методы базового класса.", "Operator_0_cannot_be_applied_to_type_1_2736": "Не удается применить операнд \"{0}\" к типу \"{1}\".", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Оператор \"{0}\" невозможно применить к типам \"{1}\" и \"{2}\".", - "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Параметр \"{0}\" можно указать только в файле tsconfig.json.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "Параметр \"{0}\" можно указать только в файле \"tsconfig.json\" либо задать значение \"false\" или \"null\" для этого параметра в командной строке.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "Параметр \"{0}\" можно указать только в файле \"tsconfig.json\" либо задать значение \"null\" для этого параметра в командной строке.", "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Параметр \"{0}\" можно использовать только при указании \"--inlineSourceMap\" или \"--sourceMap\".", "Option_0_cannot_be_specified_when_option_target_is_ES3_5048": "Параметр \"{0}\" не может быть указан, если параметр \"target\" имеет значение \"ES3\".", "Option_0_cannot_be_specified_with_option_1_5053": "Параметр \"{0}\" невозможно указать с помощью параметра \"{1}\".", @@ -1180,6 +1182,7 @@ "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Тип операнда \"await\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Типом значения вычисляемого свойства является \"{0}\", который не может быть назначен типу \"{1}\".", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Тип элементов итерации для операнда \"yield*\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Type of property '{0}' circularly references itself in mapped type '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Тип операнда \"yield\" в асинхронном генераторе должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Тип происходит от этого импорта. Импорт стиля пространства имен не может быть вызван или создан и приведет к сбою во время выполнения. Вместо этого рекомендуется использовать импорт по умолчанию или импорт, указанный здесь.", "Type_parameter_0_has_a_circular_constraint_2313": "Параметр типа \"{0}\" содержит циклическое ограничение.", diff --git a/lib/tsc.js b/lib/tsc.js index 57232444479..a5551a1c254 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -4717,6 +4717,7 @@ var ts; Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), + Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -11140,6 +11141,15 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; + function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument); + } + ts.isRequireVariableDeclaration = isRequireVariableDeclaration; + function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) { + if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + } + ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement; function isSingleOrDoubleQuote(charCode) { return charCode === 39 || charCode === 34; } @@ -11659,19 +11669,21 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - return getHostSignatureFromJSDocHost(getJSDocHost(node)); + var host = getEffectiveJSDocHost(node); + return host && ts.isFunctionLike(host) ? host : undefined; } ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; - function getHostSignatureFromJSDocHost(host) { + function getEffectiveJSDocHost(node) { + var host = getJSDocHost(node); var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || host; - return decl && ts.isFunctionLike(decl) ? decl : undefined; + return decl; } - ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + ts.getEffectiveJSDocHost = getEffectiveJSDocHost; function getJSDocHost(node) { return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent; } @@ -28460,6 +28472,9 @@ var ts; getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleName: function (moduleSpecifier) { + return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, true); + }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, tryGetThisTypeAt: function (node, includeGlobalThis) { node = ts.getParseTreeNode(node); @@ -29989,7 +30004,7 @@ var ts; return resolved; } function getTargetOfExportAssignment(node, dontResolveAlias) { - var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + var expression = ts.isExportAssignment(node) ? node.expression : node.right; var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, undefined, resolved, false); return resolved; @@ -30240,8 +30255,8 @@ var ts; return getDeclarationOfJSPrototypeContainer(symbol); } } - var sig = ts.getHostSignatureFromJSDocHost(host); - if (sig) { + var sig = ts.getEffectiveJSDocHost(node); + if (sig && ts.isFunctionLike(sig)) { var symbol = getSymbolOfNode(sig); return symbol && symbol.valueDeclaration; } @@ -31174,6 +31189,7 @@ var ts; context.encounteredError = true; return undefined; } + type = getReducedType(type); if (type.flags & 1) { context.approximateLength += 3; return ts.createKeywordTypeNode(125); @@ -32779,7 +32795,7 @@ var ts; } else { var varName = getUnusedName(name, symbol); - var typeToSerialize = getWidenedType(getTypeOfSymbol(symbol)); + var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol))); if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) { serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 : 1); } @@ -33518,6 +33534,7 @@ var ts; var type; if (pattern.kind === 189) { if (declaration.dotDotDotToken) { + parentType = getReducedType(parentType); if (parentType.flags & 2 || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; @@ -34231,13 +34248,17 @@ var ts; return links.type; } function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 65536) { + var checkFlags = ts.getCheckFlags(symbol); + if (checkFlags & 65536) { return getTypeOfSymbolWithDeferredType(symbol); } - if (ts.getCheckFlags(symbol) & 1) { + if (checkFlags & 1) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 8192) { + if (checkFlags & 262144) { + return getTypeOfMappedSymbol(symbol); + } + if (checkFlags & 8192) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -34496,7 +34517,7 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReturnTypeOfSignature(constructors[0]); + baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; @@ -34530,8 +34551,8 @@ var ts; return isValidBaseType(constraint); } } - return !!(type.flags & (524288 | 67108864 | 1)) && !isGenericMappedType(type) || - !!(type.flags & 2097152) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 | 67108864 | 1) && !isGenericMappedType(type) || + type.flags & 2097152 && ts.every(type.types, isValidBaseType)); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -34540,7 +34561,7 @@ var ts; if (declaration.kind === 246 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); + var baseType = getReducedType(getTypeFromTypeNode(node)); if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -35533,7 +35554,6 @@ var ts; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); function addMemberForKeyType(t) { var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); - var propType = instantiateType(templateType, templateMapper); if (isTypeUsableAsPropertyName(t)) { var propName = getPropertyNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); @@ -35541,10 +35561,10 @@ var ts; !(templateModifiers & 8) && modifiersProp && modifiersProp.flags & 16777216); var isReadonly = !!(templateModifiers & 1 || !(templateModifiers & 2) && modifiersProp && isReadonlySymbol(modifiersProp)); - var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName, isReadonly ? 8 : 0); - prop.type = strictNullChecks && isOptional && !maybeTypeOfKind(propType, 32768 | 16384) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 ? getTypeWithFacts(propType, 524288) : - propType; + var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216; + var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName, 262144 | (isReadonly ? 8 : 0) | (stripOptional ? 524288 : 0)); + prop.mappedType = type; + prop.mapper = templateMapper; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; prop.declarations = modifiersProp.declarations; @@ -35552,14 +35572,35 @@ var ts; prop.nameType = t; members.set(propName, prop); } - else if (t.flags & (1 | 4)) { - stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1)); - } - else if (t.flags & (8 | 32)) { - numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1)); + else if (t.flags & (1 | 4 | 8 | 32)) { + var propType = instantiateType(templateType, templateMapper); + if (t.flags & (1 | 4)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1)); + } + else { + numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1)); + } } } } + function getTypeOfMappedSymbol(symbol) { + if (!symbol.type) { + if (!pushTypeResolution(symbol, 0)) { + return errorType; + } + var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType); + var propType = instantiateType(templateType, symbol.mapper); + var type = strictNullChecks && symbol.flags & 16777216 && !maybeTypeOfKind(propType, 32768 | 16384) ? getOptionalType(propType) : + symbol.checkFlags & 524288 ? getTypeWithFacts(propType, 524288) : + propType; + if (!popTypeResolution()) { + error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType)); + type = errorType; + } + symbol.type = type; + } + return symbol.type; + } function getTypeParameterFromMappedType(type) { return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); @@ -35682,7 +35723,7 @@ var ts; return type.resolvedProperties; } function getPropertiesOfType(type) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); return type.flags & 3145728 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); @@ -35975,7 +36016,7 @@ var ts; for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var current = _a[_i]; var type = getApparentType(current); - if (type !== errorType) { + if (!(type === errorType || type.flags & 131072)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { @@ -36047,6 +36088,9 @@ var ts; if (isLiteralType(type)) { checkFlags |= 128; } + if (type.flags & 131072) { + checkFlags |= 131072; + } propTypes.push(type); } ts.addRange(propTypes, indexTypes); @@ -36085,8 +36129,37 @@ var ts; var property = getUnionOrIntersectionProperty(type, name); return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } + function getReducedType(type) { + if (type.flags & 1048576 && type.objectFlags & 268435456) { + return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); + } + else if (type.flags & 2097152) { + if (!(type.objectFlags & 268435456)) { + type.objectFlags |= 268435456 | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 : 0); + } + return type.objectFlags & 536870912 ? neverType : type; + } + return type; + } + function getReducedUnionType(unionType) { + var reducedTypes = ts.sameMap(unionType.types, getReducedType); + if (reducedTypes === unionType.types) { + return unionType; + } + var reduced = getUnionType(reducedTypes); + if (reduced.flags & 1048576) { + reduced.resolvedReducedType = reduced; + } + return reduced; + } + function isDiscriminantWithNeverType(prop) { + return !(prop.flags & 16777216) && + (ts.getCheckFlags(prop) & (192 | 131072)) === 192 && + !!(getTypeOfSymbol(prop).flags & 131072); + } function getPropertyOfType(type, name) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); if (type.flags & 524288) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); @@ -36118,7 +36191,7 @@ var ts; return ts.emptyArray; } function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); + return getSignaturesOfStructuredType(getApparentType(getReducedType(type)), kind); } function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 3670016) { @@ -36131,10 +36204,10 @@ var ts; return info && info.type; } function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); + return getIndexInfoOfStructuredType(getApparentType(getReducedType(type)), kind); } function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); + return getIndexTypeOfStructuredType(getApparentType(getReducedType(type)), kind); } function getImplicitIndexTypeOfType(type, kind) { if (isObjectTypeWithInferableIndex(type)) { @@ -37310,14 +37383,14 @@ var ts; return addTypesToUnion(typeSet, includes, type.types); } if (!(flags & 131072)) { - includes |= flags & 68943871; + includes |= flags & 71041023; if (flags & 66846720) includes |= 262144; if (type === wildcardType) - includes |= 4194304; + includes |= 8388608; if (!strictNullChecks && flags & 98304) { if (!(ts.getObjectFlags(type) & 524288)) - includes |= 2097152; + includes |= 4194304; } else { var len = typeSet.length; @@ -37409,7 +37482,7 @@ var ts; var includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0) { if (includes & 3) { - return includes & 1 ? includes & 4194304 ? wildcardType : anyType : unknownType; + return includes & 1 ? includes & 8388608 ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1: @@ -37424,12 +37497,14 @@ var ts; break; } if (typeSet.length === 0) { - return includes & 65536 ? includes & 2097152 ? nullType : nullWideningType : - includes & 32768 ? includes & 2097152 ? undefinedType : undefinedWideningType : + return includes & 65536 ? includes & 4194304 ? nullType : nullWideningType : + includes & 32768 ? includes & 4194304 ? undefinedType : undefinedWideningType : neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 ? 0 : 262144, aliasSymbol, aliasTypeArguments); + var objectFlags = (includes & 66994211 ? 0 : 262144) | + (includes & 2097152 ? 268435456 : 0); + return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37492,15 +37567,15 @@ var ts; return addTypesToIntersection(typeSet, includes, type.types); } if (isEmptyAnonymousObjectType(type)) { - if (!(includes & 8388608)) { - includes |= 8388608; + if (!(includes & 16777216)) { + includes |= 16777216; typeSet.set(type.id.toString(), type); } } else { if (flags & 3) { if (type === wildcardType) - includes |= 4194304; + includes |= 8388608; } else if ((strictNullChecks || !(flags & 98304)) && !typeSet.has(type.id.toString())) { if (type.flags & 109440 && includes & 109440) { @@ -37508,7 +37583,7 @@ var ts; } typeSet.set(type.id.toString(), type); } - includes |= flags & 68943871; + includes |= flags & 71041023; } return includes; } @@ -37607,7 +37682,7 @@ var ts; var includes = addTypesToIntersection(typeMembershipMap, 0, types); var typeSet = ts.arrayFrom(typeMembershipMap.values()); if (includes & 131072 || - strictNullChecks && includes & 98304 && includes & (524288 | 67108864 | 8388608) || + strictNullChecks && includes & 98304 && includes & (524288 | 67108864 | 16777216) || includes & 67108864 && includes & (67238908 & ~67108864) || includes & 132 && includes & (67238908 & ~132) || includes & 296 && includes & (67238908 & ~296) || @@ -37617,7 +37692,7 @@ var ts; return neverType; } if (includes & 1) { - return includes & 4194304 ? wildcardType : anyType; + return includes & 8388608 ? wildcardType : anyType; } if (!strictNullChecks && includes & 98304) { return includes & 32768 ? undefinedType : nullType; @@ -37628,7 +37703,7 @@ var ts; includes & 4096 && includes & 8192) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 8388608 && includes & 524288) { + if (includes & 16777216 && includes & 524288) { ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { @@ -37727,6 +37802,7 @@ var ts; } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + type = getReducedType(type); return type.flags & 1048576 ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : type.flags & 2097152 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : maybeTypeOfKind(type, 58982400) ? getIndexTypeForGenericType(type, stringsOnly) : @@ -38070,7 +38146,7 @@ var ts; } return type; } - var apparentObjectType = getApparentType(objectType); + var apparentObjectType = getApparentType(getReducedType(objectType)); if (indexType.flags & 1048576 && !(indexType.flags & 16)) { var propTypes = []; var wasMissingProp = false; @@ -38879,7 +38955,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { + return mapType(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 | 58982400 | 524288 | 2097152) && t !== wildcardType && t !== errorType) { var replacementMapper = createReplacementMapper(typeVariable, t, mapper); return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) : @@ -39837,7 +39913,8 @@ var ts; } } else { - if (!(source.flags === target.flags && source.flags & 66584576)) + if (!(source.flags & 3145728) && !(target.flags & 3145728) && + source.flags !== target.flags && !(source.flags & 66584576)) return false; } if (source.flags & 524288 && target.flags & 524288) { @@ -39855,16 +39932,17 @@ var ts; return ts.getObjectFlags(source) & 4096 && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { - do { + while (true) { var t = isFreshLiteralType(type) ? type.regularType : ts.getObjectFlags(type) & 4 && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 33554432 ? writing ? type.typeVariable : type.substitute : - type.flags & 25165824 ? getSimplifiedType(type, writing) : - type; + type.flags & 3145728 ? getReducedType(type) : + type.flags & 33554432 ? writing ? type.typeVariable : type.substitute : + type.flags & 25165824 ? getSimplifiedType(type, writing) : + type; if (t === type) break; type = t; - } while (true); + } return type; } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { @@ -42555,6 +42633,7 @@ var ts; } } else { + source = getReducedType(source); if (!(priority & 128 && source.flags & (2097152 | 63176704))) { var apparentSource = getApparentType(source); if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 | 2097152))) { @@ -43097,9 +43176,6 @@ var ts; } return false; } - function isSyntheticThisPropertyAccess(expr) { - return ts.isAccessExpression(expr) && expr.expression.kind === 104 && !!(expr.expression.flags & 8); - } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -44225,9 +44301,6 @@ var ts; if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { return getTypeWithFacts(type, 2097152); } - if (containsMatchingReference(reference, target)) { - return declaredType; - } return type; } if (type.flags & 1 && literal.text === "function") { @@ -44359,9 +44432,6 @@ var ts; if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { return getTypeWithFacts(type, 2097152); } - if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) { - return declaredType; - } return type; } var rightType = getTypeOfExpression(expr.right); @@ -44423,9 +44493,6 @@ var ts; !(getTypeFacts(predicate.type) & 65536)) { return getTypeWithFacts(type, 2097152); } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } } } return type; @@ -46040,7 +46107,7 @@ var ts; hasComputedStringProperty = false; hasComputedNumberProperty = false; } - var type = checkExpression(memberDecl.expression); + var type = getReducedType(checkExpression(memberDecl.expression)); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; @@ -46199,7 +46266,7 @@ var ts; spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, false); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -52012,15 +52079,14 @@ var ts; checkSignatureDeclaration(node); } function checkJSDocImplementsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); - return; } } function checkJSDocAugmentsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } @@ -53660,7 +53726,7 @@ var ts; } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); + var t = getReducedType(getTypeFromTypeNode(typeRefNode)); if (t !== errorType) { if (isValidBaseType(t)) { var genericDiag = t.symbol && t.symbol.flags & 32 ? @@ -61868,9 +61934,7 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) - ? target.expression - : target; + return target; } } ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; @@ -64472,7 +64536,7 @@ var ts; } var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, iife) - ], languageVersion > 1 ? 2 : undefined)); + ], languageVersion > 1 ? 1 : undefined)); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); @@ -65504,8 +65568,8 @@ var ts; if (node.isTypeOnly) { return undefined; } - if (!node.exportClause) { - return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) { + return node; } if (!resolver.isValueAliasDeclaration(node)) { return undefined; diff --git a/lib/tsserver.js b/lib/tsserver.js index 7af972f5cbd..03bd6a47cad 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -3770,6 +3770,9 @@ var ts; CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter"; CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter"; CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType"; + CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType"; + CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped"; + CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant"; CheckFlags[CheckFlags["Partial"] = 48] = "Partial"; @@ -3896,16 +3899,16 @@ var ts; TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ - TypeFlags[TypeFlags["IncludesMask"] = 68943871] = "IncludesMask"; + TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask"; // The following flags are used for different purposes during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable"; /* @internal */ - TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType"; + TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType"; /* @internal */ - TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard"; + TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ - TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject"; + TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -3947,6 +3950,12 @@ var ts; ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; /* @internal */ ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; @@ -7190,6 +7199,7 @@ var ts; Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), + Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -14366,6 +14376,15 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; + function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument); + } + ts.isRequireVariableDeclaration = isRequireVariableDeclaration; + function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) { + if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + } + ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement; function isSingleOrDoubleQuote(charCode) { return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } @@ -14944,19 +14963,22 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - return getHostSignatureFromJSDocHost(getJSDocHost(node)); + var host = getEffectiveJSDocHost(node); + return host && ts.isFunctionLike(host) ? host : undefined; } ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; - function getHostSignatureFromJSDocHost(host) { + function getEffectiveJSDocHost(node) { + var host = getJSDocHost(node); var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || host; - return decl && ts.isFunctionLike(decl) ? decl : undefined; + return decl; } - ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + ts.getEffectiveJSDocHost = getEffectiveJSDocHost; + /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */ function getJSDocHost(node) { return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent; } @@ -34801,6 +34823,9 @@ var ts; getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleName: function (moduleSpecifier) { + return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); + }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, tryGetThisTypeAt: function (node, includeGlobalThis) { node = ts.getParseTreeNode(node); @@ -36586,7 +36611,7 @@ var ts; return resolved; } function getTargetOfExportAssignment(node, dontResolveAlias) { - var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + var expression = ts.isExportAssignment(node) ? node.expression : node.right; var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); return resolved; @@ -36894,8 +36919,8 @@ var ts; return getDeclarationOfJSPrototypeContainer(symbol); } } - var sig = ts.getHostSignatureFromJSDocHost(host); - if (sig) { + var sig = ts.getEffectiveJSDocHost(node); + if (sig && ts.isFunctionLike(sig)) { var symbol = getSymbolOfNode(sig); return symbol && symbol.valueDeclaration; } @@ -37957,6 +37982,7 @@ var ts; context.encounteredError = true; return undefined; // TODO: GH#18217 } + type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -39810,7 +39836,7 @@ var ts; var varName = getUnusedName(name, symbol); // We have to use `getWidenedType` here since the object within a json file is unwidened within the file // (Unwidened types can only exist in expression contexts and should never be serialized) - var typeToSerialize = getWidenedType(getTypeOfSymbol(symbol)); + var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol))); if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) { // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */); @@ -40665,6 +40691,7 @@ var ts; var type; if (pattern.kind === 189 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { + parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; @@ -41476,13 +41503,17 @@ var ts; return links.type; } function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 65536 /* DeferredType */) { + var checkFlags = ts.getCheckFlags(symbol); + if (checkFlags & 65536 /* DeferredType */) { return getTypeOfSymbolWithDeferredType(symbol); } - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + if (checkFlags & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 8192 /* ReverseMapped */) { + if (checkFlags & 262144 /* Mapped */) { + return getTypeOfMappedSymbol(symbol); + } + if (checkFlags & 8192 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -41770,7 +41801,7 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReturnTypeOfSignature(constructors[0]); + baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; @@ -41813,8 +41844,8 @@ var ts; } // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed? // There's no reason a `T` should be allowed while a `Readonly` should not. - return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType)); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -41823,7 +41854,7 @@ var ts; if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); + var baseType = getReducedType(getTypeFromTypeNode(node)); if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -42988,7 +43019,6 @@ var ts; // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); - var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (isTypeUsableAsPropertyName(t)) { @@ -42998,13 +43028,10 @@ var ts; !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); - var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); - // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the - // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks - // mode, if the underlying property is optional we remove 'undefined' from the type. - prop.type = strictNullChecks && isOptional && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : - propType; + var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */; + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0)); + prop.mappedType = type; + prop.mapper = templateMapper; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; prop.declarations = modifiersProp.declarations; @@ -43012,14 +43039,38 @@ var ts; prop.nameType = t; members.set(propName, prop); } - else if (t.flags & (1 /* Any */ | 4 /* String */)) { - stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); - } - else if (t.flags & (8 /* Number */ | 32 /* Enum */)) { - numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) { + var propType = instantiateType(templateType, templateMapper); + if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else { + numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } } } } + function getTypeOfMappedSymbol(symbol) { + if (!symbol.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType); + var propType = instantiateType(templateType, symbol.mapper); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : + symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (!popTypeResolution()) { + error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType)); + type = errorType; + } + symbol.type = type; + } + return symbol.type; + } function getTypeParameterFromMappedType(type) { return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); @@ -43154,7 +43205,7 @@ var ts; return type.resolvedProperties; } function getPropertiesOfType(type) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); @@ -43473,7 +43524,7 @@ var ts; /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the - * type itself. Note that the apparent type of a union type is the union type itself. + * type itself. */ function getApparentType(type) { var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; @@ -43501,7 +43552,7 @@ var ts; for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var current = _a[_i]; var type = getApparentType(current); - if (type !== errorType) { + if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { @@ -43573,6 +43624,9 @@ var ts; if (isLiteralType(type)) { checkFlags |= 128 /* HasLiteralType */; } + if (type.flags & 131072 /* Never */) { + checkFlags |= 131072 /* HasNeverType */; + } propTypes.push(type); } ts.addRange(propTypes, indexTypes); @@ -43619,6 +43673,41 @@ var ts; // We need to filter out partial properties in union types return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined; } + /** + * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types. + * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'. + * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when + * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. + */ + function getReducedType(type) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); + } + else if (type.flags & 2097152 /* Intersection */) { + if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + } + return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + } + return type; + } + function getReducedUnionType(unionType) { + var reducedTypes = ts.sameMap(unionType.types, getReducedType); + if (reducedTypes === unionType.types) { + return unionType; + } + var reduced = getUnionType(reducedTypes); + if (reduced.flags & 1048576 /* Union */) { + reduced.resolvedReducedType = reduced; + } + return reduced; + } + function isDiscriminantWithNeverType(prop) { + return !(prop.flags & 16777216 /* Optional */) && + (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && + !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -43628,7 +43717,7 @@ var ts; * @param name a name of property to look up in a given type */ function getPropertyOfType(type, name) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); @@ -43664,7 +43753,7 @@ var ts; * maps primitive types and type parameters are to their apparent types. */ function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); + return getSignaturesOfStructuredType(getApparentType(getReducedType(type)), kind); } function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 3670016 /* StructuredType */) { @@ -43679,12 +43768,12 @@ var ts; // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); + return getIndexInfoOfStructuredType(getApparentType(getReducedType(type)), kind); } // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); + return getIndexTypeOfStructuredType(getApparentType(getReducedType(type)), kind); } function getImplicitIndexTypeOfType(type, kind) { if (isObjectTypeWithInferableIndex(type)) { @@ -44966,14 +45055,14 @@ var ts; } // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; if (flags & 66846720 /* StructuredOrInstantiable */) includes |= 262144 /* IncludesStructuredOrInstantiable */; if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) - includes |= 2097152 /* IncludesNonWideningType */; + includes |= 4194304 /* IncludesNonWideningType */; } else { var len = typeSet.length; @@ -45079,7 +45168,7 @@ var ts; var includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */) { if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; + return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1 /* Literal */: @@ -45094,12 +45183,14 @@ var ts; break; } if (typeSet.length === 0) { - return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType : - includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : + return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -45171,15 +45262,15 @@ var ts; return addTypesToIntersection(typeSet, includes, type.types); } if (isEmptyAnonymousObjectType(type)) { - if (!(includes & 8388608 /* IncludesEmptyObject */)) { - includes |= 8388608 /* IncludesEmptyObject */; + if (!(includes & 16777216 /* IncludesEmptyObject */)) { + includes |= 16777216 /* IncludesEmptyObject */; typeSet.set(type.id.toString(), type); } } else { if (flags & 3 /* AnyOrUnknown */) { if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; } else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) { if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) { @@ -45189,7 +45280,7 @@ var ts; } typeSet.set(type.id.toString(), type); } - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; } return includes; } @@ -45322,7 +45413,7 @@ var ts; // a void-like type and a type known to be non-void-like, or // a non-primitive type and a type known to be primitive. if (includes & 131072 /* Never */ || - strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 8388608 /* IncludesEmptyObject */) || + strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) || includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || @@ -45332,7 +45423,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType; + return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType; } if (!strictNullChecks && includes & 98304 /* Nullable */) { return includes & 32768 /* Undefined */ ? undefinedType : nullType; @@ -45343,7 +45434,7 @@ var ts; includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { + if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { @@ -45448,6 +45539,7 @@ var ts; } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + type = getReducedType(type); return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : @@ -45837,7 +45929,7 @@ var ts; // In the following we resolve T[K] to the type of the property in T selected by K. // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. - var apparentObjectType = getApparentType(objectType); + var apparentObjectType = getApparentType(getReducedType(objectType)); if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; var wasMissingProp = false; @@ -46733,7 +46825,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { + return mapType(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { var replacementMapper = createReplacementMapper(typeVariable, t, mapper); return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) : @@ -47795,7 +47887,8 @@ var ts; } } else { - if (!(source.flags === target.flags && source.flags & 66584576 /* Substructure */)) + if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) && + source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */)) return false; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { @@ -47813,16 +47906,17 @@ var ts; return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { - do { + while (true) { var t = isFreshLiteralType(type) ? type.regularType : ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : - type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : - type; + type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) : + type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : + type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : + type; if (t === type) break; type = t; - } while (true); + } return type; } /** @@ -50971,6 +51065,7 @@ var ts; } } else { + source = getReducedType(source); if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. @@ -51593,9 +51688,6 @@ var ts; } return false; } - function isSyntheticThisPropertyAccess(expr) { - return ts.isAccessExpression(expr) && expr.expression.kind === 104 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */); - } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -52846,11 +52938,6 @@ var ts; if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { - return declaredType; - } return type; } if (type.flags & 1 /* Any */ && literal.text === "function") { @@ -53024,16 +53111,6 @@ var ts; if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' - // references might reference a different 'y' property. However, we make an exception - // for property accesses where x is a synthetic 'this' expression, indicating that we - // were called from isPropertyInitializedInConstructor. Without this exception, - // initializations of 'this' properties that occur before a 'this instanceof XXX' - // check would not be considered. - if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) { - return declaredType; - } return type; } // Check that right operand is a function type with a prototype property @@ -53106,9 +53183,6 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } } } return type; @@ -55067,7 +55141,7 @@ var ts; hasComputedStringProperty = false; hasComputedNumberProperty = false; } - var type = checkExpression(memberDecl.expression); + var type = getReducedType(checkExpression(memberDecl.expression)); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; @@ -55254,7 +55328,7 @@ var ts; spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -62078,15 +62152,14 @@ var ts; checkSignatureDeclaration(node); } function checkJSDocImplementsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); - return; } } function checkJSDocAugmentsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } @@ -64113,7 +64186,7 @@ var ts; } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); + var t = getReducedType(getTypeFromTypeNode(typeRefNode)); if (t !== errorType) { if (isValidBaseType(t)) { var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? @@ -73322,9 +73395,7 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) - ? target.expression - : target; + return target; } } ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; @@ -76493,7 +76564,7 @@ var ts; /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), /*type*/ undefined, iife) - ], languageVersion > 1 /* ES5 */ ? 2 /* Const */ : undefined)); + ], languageVersion > 1 /* ES5 */ ? 1 /* Let */ : undefined)); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); @@ -78232,9 +78303,11 @@ var ts; if (node.isTypeOnly) { return undefined; } - if (!node.exportClause) { - // Elide a star export if the module it references does not export a value. - return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) { + // never elide `export from ` declarations - + // they should be kept for sideffects/untyped exports, even when the + // type checker doesn't know about any exports + return node; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -107458,6 +107531,10 @@ var ts; : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); } ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsModules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); }); + } + ts.programContainsModules = programContainsModules; function programContainsEs6Modules(program) { return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); } @@ -107595,7 +107672,8 @@ var ts; } ts.findModifier = findModifier; function insertImport(changes, sourceFile, importDecl, blankLineBetween) { - var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var importKindPredicate = importDecl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; + var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); }); if (lastImportDeclaration) { changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); } @@ -111166,20 +111244,17 @@ var ts; filterGlobalCompletion(symbols); } function shouldOfferImportCompletions() { - // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs) + // If not already a module, must have modules enabled. if (!preferences.includeCompletionsForModuleExports) return false; // If already using ES6 modules, OK to continue using them. - if (sourceFile.externalModuleIndicator) + if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; - // If already using commonjs, don't introduce ES6. - if (sourceFile.commonJsModuleIndicator) - return false; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) return true; // If some file is using ES6 modules, assume that it's OK to add more. - return ts.programContainsEs6Modules(program); + return ts.programContainsModules(program); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { @@ -111322,6 +111397,7 @@ var ts; var startTime = ts.timestamp(); log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : "")); var seenResolvedModules = ts.createMap(); + var seenExports = ts.createMap(); /** Bucket B */ var aliasesToAlreadyIncludedSymbols = ts.createMap(); /** Bucket C */ @@ -111342,17 +111418,20 @@ var ts; } // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { + if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, isNonGlobalDeclaration)) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } - for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; + var symbolId = ts.getSymbolId(symbol).toString(); + // `getExportsAndPropertiesOfModule` can include duplicates + if (!ts.addToSeen(seenExports, symbolId)) { + continue; + } // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) { continue; } - var symbolId = ts.getSymbolId(symbol).toString(); // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol; // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). @@ -112336,6 +112415,15 @@ var ts; } } } + function isNonGlobalDeclaration(declaration) { + var sourceFile = declaration.getSourceFile(); + // If the file is not a module, the declaration is global + if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { + return false; + } + // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation + return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -128381,7 +128469,8 @@ var ts; var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker)); var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, sourceFile, compilerOptions, checker, program.getSourceFiles()); var preferTypeOnlyImport = !!usageIsTypeOnly && compilerOptions.importsNotUsedAsValues === 2 /* Error */; - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, host, preferences); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, useRequire, host, preferences); addImport({ fixes: [fix], symbolName: symbolName }); } function addImport(info) { @@ -128395,11 +128484,11 @@ var ts; importType.push(fix); break; case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - var key = String(ts.getNodeId(importClause)); + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; + var key = String(ts.getNodeId(importClauseOrBindingPattern)); var entry = addToExisting.get(key); if (!entry) { - addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); + addToExisting.set(key, entry = { importClauseOrBindingPattern: importClauseOrBindingPattern, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); } if (importKind === 0 /* Named */) { ts.pushIfUnique(entry.namedImports, symbolName); @@ -128411,10 +128500,10 @@ var ts; break; } case 3 /* AddNew */: { - var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, typeOnly = fix.typeOnly; + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, useRequire = fix.useRequire, typeOnly = fix.typeOnly; var entry = newImports.get(moduleSpecifier); if (!entry) { - newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly }); + newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire }); lastModuleSpecifier = moduleSpecifier; } else { @@ -128427,9 +128516,9 @@ var ts; entry.defaultImport = symbolName; break; case 0 /* Named */: - ts.pushIfUnique(entry.namedImports, symbolName); + ts.pushIfUnique(entry.namedImports || (entry.namedImports = []), symbolName); break; - case 3 /* Equals */: + case 3 /* CommonJS */: case 2 /* Namespace */: ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName, "Namespacelike import shoudl be missing or match symbolName"); entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; @@ -128452,11 +128541,13 @@ var ts; addImportType(changeTracker, sourceFile, fix, quotePreference); } addToExisting.forEach(function (_a) { - var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; - doAddExistingFix(changeTracker, sourceFile, importClause, defaultImport, namedImports, canUseTypeOnlyImport); + var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; + doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport); }); - newImports.forEach(function (imports, moduleSpecifier) { - addNewImports(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); + newImports.forEach(function (_a, moduleSpecifier) { + var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]); + var addDeclarations = useRequire ? addNewRequires : addNewImports; + addDeclarations(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); }); } } @@ -128474,22 +128565,22 @@ var ts; ImportKind[ImportKind["Named"] = 0] = "Named"; ImportKind[ImportKind["Default"] = 1] = "Default"; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["Equals"] = 3] = "Equals"; - ImportKind[ImportKind["ConstEquals"] = 4] = "ConstEquals"; + ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, sourceFile, compilerOptions, program.getTypeChecker(), program.getSourceFiles()); - var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, exportInfos, host, preferences)).moduleSpecifier; - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, host, preferences); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, host, preferences) { + function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, program, sourceFile, host, preferences)); + return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -128506,7 +128597,7 @@ var ts; if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); } - for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); @@ -128523,13 +128614,13 @@ var ts; } function getFixForImport(exportInfos, symbolName, /** undefined only for missing JSX namespace */ - position, preferTypeOnlyImport, program, sourceFile, host, preferences) { + position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. - var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, host, preferences); + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences); return __spreadArrays((useNamespace ? [useNamespace] : ts.emptyArray), addImport); } function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { @@ -128547,58 +128638,91 @@ var ts; // and it is up to the user to decide which one fits best. return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + var namespacePrefix = getNamespaceLikeImportText(declaration); + if (namespacePrefix) { + var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position }; } } }); } + function getTargetModuleFromNamespaceLikeImport(declaration, checker) { + var _a; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); + case 253 /* ImportEqualsDeclaration */: + return checker.getAliasedSymbol(declaration.symbol); + case 254 /* ImportDeclaration */: + var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); + return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); + default: + return ts.Debug.assertNever(declaration); + } + } + function getNamespaceLikeImportText(declaration) { + var _a, _b, _c; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; + case 253 /* ImportEqualsDeclaration */: + return declaration.name.text; + case 254 /* ImportDeclaration */: + return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; + default: + return ts.Debug.assertNever(declaration); + } + } function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind !== 254 /* ImportDeclaration */) + if (declaration.kind === 253 /* ImportEqualsDeclaration */) return undefined; + if (declaration.kind === 242 /* VariableDeclaration */) { + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 189 /* ObjectBindingPattern */ + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false } + : undefined; + } var importClause = declaration.importClause; if (!importClause) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 257 /* NamedImports */) - ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind, canUseTypeOnlyImport: canUseTypeOnlyImport } + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; }); } - function getNamespaceImportName(declaration) { - if (declaration.kind === 254 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 256 /* NamespaceImport */ ? namedBindings.name : undefined; - } - else { - return declaration.name; - } - } function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) - && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, exportedSymbolIsTypeOnly: exportedSymbolIsTypeOnly } : undefined; + if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined; + } + if (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) { + return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + } }); } - function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, moduleSymbols, host, preferences) { + function shouldUseRequire(sourceFile, compilerOptions) { + return ts.isSourceFileJS(sourceFile) + && !sourceFile.externalModuleIndicator + && (!!sourceFile.commonJsModuleIndicator || ts.getEmitModuleKind(compilerOptions) < ts.ModuleKind.ES2015); + } + function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); + var compilerOptions = program.getCompilerOptions(); var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, compilerOptions, sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.checkDefined(position, "position should be defined") } - : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, typeOnly: preferTypeOnlyImport }; + : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; }); }); // Sort by presence in package.json, then shortest paths first @@ -128614,19 +128738,18 @@ var ts; return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } - function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, host, preferences) { - var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport); }); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, exportInfos, host, preferences); + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } - function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport) { + function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 254 /* ImportDeclaration */ - ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 265 /* ExternalModuleReference */ - ? declaration.moduleReference.expression - : undefined; - return expression && ts.isStringLiteral(expression) - ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind, typeOnly: preferTypeOnlyImport } + var moduleSpecifier = declaration.kind === 254 /* ImportDeclaration */ ? declaration.moduleSpecifier : + declaration.kind === 242 /* VariableDeclaration */ ? declaration.initializer.arguments[0] : + declaration.moduleReference.kind === 265 /* ExternalModuleReference */ ? declaration.moduleReference.expression : + undefined; + return moduleSpecifier && ts.isStringLiteral(moduleSpecifier) + ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } : undefined; } function getFixesInfo(context, errorCode, pos) { @@ -128645,7 +128768,8 @@ var ts; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; - var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, program, sourceFile, host, preferences); + var useRequire = shouldUseRequire(sourceFile, program.getCompilerOptions()); + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -128671,9 +128795,9 @@ var ts; case ts.ModuleKind.CommonJS: case ts.ModuleKind.UMD: if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 3 /* CommonJS */; } - return 3 /* Equals */; + return 3 /* CommonJS */; case ts.ModuleKind.System: case ts.ModuleKind.ES2015: case ts.ModuleKind.ES2020: @@ -128696,11 +128820,13 @@ var ts; : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); - var preferTypeOnlyImport = program.getCompilerOptions().importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); + var compilerOptions = program.getCompilerOptions(); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program, host); var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, program, sourceFile, host, preferences); + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } @@ -128751,7 +128877,7 @@ var ts; // 2. 'import =' will not work in JavaScript, so the decision is between a default // and const/require. if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 1 /* Default */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 1 /* Default */ : 3 /* CommonJS */; } // 3. At this point the most correct choice is probably 'import =', but people // really hate that, so look to see if the importing file has any precedent @@ -128759,12 +128885,12 @@ var ts; for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (ts.isImportEqualsDeclaration(statement)) { - return 3 /* Equals */; + return 3 /* CommonJS */; } } // 4. We have no precedent to go on, so just use a default import if // allowSyntheticDefaultImports/esModuleInterop is enabled. - return allowSyntheticDefaults ? 1 /* Default */ : 3 /* Equals */; + return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); @@ -128812,16 +128938,18 @@ var ts; addImportType(changes, sourceFile, fix, quotePreference); return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport, moduleSpecifier = fix.moduleSpecifier; + doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! } case 3 /* AddNew */: { - var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly; - addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined, typeOnly: typeOnly } - : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined, typeOnly: typeOnly } - : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }, /*blankLineBetween*/ true); + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire; + var addDeclarations = useRequire ? addNewRequires : addNewImports; + var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } : + importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } : + { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }; + addDeclarations(changes, sourceFile, moduleSpecifier, quotePreference, importsCollection, /*blankLineBetween*/ true); return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: @@ -128829,6 +128957,16 @@ var ts; } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) { + if (clause.kind === 189 /* ObjectBindingPattern */) { + if (defaultImport) { + addElementToBindingPattern(clause, defaultImport, "default"); + } + for (var _i = 0, namedImports_1 = namedImports; _i < namedImports_1.length; _i++) { + var specifier = namedImports_1[_i]; + addElementToBindingPattern(clause, specifier, /*propertyName*/ undefined); + } + return; + } var convertTypeOnlyToRegular = !canUseTypeOnlyImport && clause.isTypeOnly; if (defaultImport) { ts.Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one"); @@ -128837,19 +128975,19 @@ var ts; if (namedImports.length) { var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { - for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { - var spec = specifiers_1[_i]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var spec = specifiers_1[_a]; changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); } } else { if (specifiers.length) { - var namedImports_1 = ts.createNamedImports(specifiers); + var namedImports_2 = ts.createNamedImports(specifiers); if (clause.namedBindings) { - changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_2); } else { - changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_1); + changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_2); } } } @@ -128857,6 +128995,15 @@ var ts; if (convertTypeOnlyToRegular) { changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(clause, sourceFile)); } + function addElementToBindingPattern(bindingPattern, name, propertyName) { + var element = ts.createBindingElement(/*dotDotDotToken*/ undefined, propertyName, name); + if (bindingPattern.elements.length) { + changes.insertNodeInListAfter(sourceFile, ts.last(bindingPattern.elements), element); + } + else { + changes.replaceNode(sourceFile, bindingPattern, ts.createObjectBindingPattern([element])); + } + } } function addNamespaceQualifier(changes, sourceFile, _a) { var namespacePrefix = _a.namespacePrefix, position = _a.position; @@ -128870,21 +129017,47 @@ var ts; var quote = ts.getQuoteFromPreference(quotePreference); return "import(" + quote + moduleSpecifier + quote + ")."; } - function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a, blankLineBetween) { - var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport, typeOnly = _a.typeOnly; + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); - if (defaultImport !== undefined || namedImports.length) { - ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, typeOnly), /*blankLineBetween*/ blankLineBetween); + if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + ts.insertImport(changes, sourceFile, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly), /*blankLineBetween*/ blankLineBetween); } + var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly; if (namespaceLikeImport) { - ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) : - namespaceLikeImport.importKind === 4 /* ConstEquals */ ? createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier) : - ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier), /*blankLineBetween*/ blankLineBetween); + var declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ + ? ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause( + /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, /*blankLineBetween*/ blankLineBetween); + } + } + function addNewRequires(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + var _a, _b; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + // const { default: foo, bar, etc } = require('./mod'); + if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || []; + if (imports.defaultImport) { + bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport)); + } + var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + } + // const foo = require('./mod'); + if (imports.namespaceLikeImport) { + var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, blankLineBetween); } } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.createIdentifier(name), + return ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(typeof name === "string" ? ts.createIdentifier(name) : name, /*type*/ undefined, ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier])) ], 2 /* Const */)); } @@ -135308,7 +135481,7 @@ var ts; get: function () { return ts.symbolName(this); }, - enumerable: true, + enumerable: false, configurable: true }); SymbolObject.prototype.getEscapedName = function () { @@ -135355,7 +135528,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return IdentifierObject; @@ -135370,7 +135543,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return PrivateIdentifierObject; @@ -135463,7 +135636,7 @@ var ts; } return undefined; }, - enumerable: true, + enumerable: false, configurable: true }); return TypeObject; @@ -140119,7 +140292,7 @@ var ts; get: function () { return this.projectService.typingsCache; }, - enumerable: true, + enumerable: false, configurable: true }); /*@internal*/ @@ -147065,7 +147238,7 @@ var ts; } Object.defineProperty(EditWalker.prototype, "done", { get: function () { return false; }, - enumerable: true, + enumerable: false, configurable: true }); EditWalker.prototype.insertLines = function (insertedText, suppressTrailingText) { @@ -147928,7 +148101,7 @@ var ts; get: function () { return this.fd >= 0 || this.traceToConsole; }, - enumerable: true, + enumerable: false, configurable: true }); Logger.prototype.write = function (s) { diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index fd278a1f536..852887766ed 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -3920,6 +3920,9 @@ var ts; CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter"; CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter"; CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType"; + CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType"; + CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped"; + CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant"; CheckFlags[CheckFlags["Partial"] = 48] = "Partial"; @@ -4046,16 +4049,16 @@ var ts; TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ - TypeFlags[TypeFlags["IncludesMask"] = 68943871] = "IncludesMask"; + TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask"; // The following flags are used for different purposes during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable"; /* @internal */ - TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType"; + TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType"; /* @internal */ - TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard"; + TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ - TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject"; + TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -4097,6 +4100,12 @@ var ts; ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; /* @internal */ ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; @@ -7340,6 +7349,7 @@ var ts; Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), + Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -14516,6 +14526,15 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; + function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument); + } + ts.isRequireVariableDeclaration = isRequireVariableDeclaration; + function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) { + if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + } + ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement; function isSingleOrDoubleQuote(charCode) { return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } @@ -15094,19 +15113,22 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - return getHostSignatureFromJSDocHost(getJSDocHost(node)); + var host = getEffectiveJSDocHost(node); + return host && ts.isFunctionLike(host) ? host : undefined; } ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; - function getHostSignatureFromJSDocHost(host) { + function getEffectiveJSDocHost(node) { + var host = getJSDocHost(node); var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || host; - return decl && ts.isFunctionLike(decl) ? decl : undefined; + return decl; } - ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + ts.getEffectiveJSDocHost = getEffectiveJSDocHost; + /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */ function getJSDocHost(node) { return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent; } @@ -34951,6 +34973,9 @@ var ts; getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleName: function (moduleSpecifier) { + return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); + }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, tryGetThisTypeAt: function (node, includeGlobalThis) { node = ts.getParseTreeNode(node); @@ -36736,7 +36761,7 @@ var ts; return resolved; } function getTargetOfExportAssignment(node, dontResolveAlias) { - var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + var expression = ts.isExportAssignment(node) ? node.expression : node.right; var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); return resolved; @@ -37044,8 +37069,8 @@ var ts; return getDeclarationOfJSPrototypeContainer(symbol); } } - var sig = ts.getHostSignatureFromJSDocHost(host); - if (sig) { + var sig = ts.getEffectiveJSDocHost(node); + if (sig && ts.isFunctionLike(sig)) { var symbol = getSymbolOfNode(sig); return symbol && symbol.valueDeclaration; } @@ -38107,6 +38132,7 @@ var ts; context.encounteredError = true; return undefined; // TODO: GH#18217 } + type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -39960,7 +39986,7 @@ var ts; var varName = getUnusedName(name, symbol); // We have to use `getWidenedType` here since the object within a json file is unwidened within the file // (Unwidened types can only exist in expression contexts and should never be serialized) - var typeToSerialize = getWidenedType(getTypeOfSymbol(symbol)); + var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol))); if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) { // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */); @@ -40815,6 +40841,7 @@ var ts; var type; if (pattern.kind === 189 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { + parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; @@ -41626,13 +41653,17 @@ var ts; return links.type; } function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 65536 /* DeferredType */) { + var checkFlags = ts.getCheckFlags(symbol); + if (checkFlags & 65536 /* DeferredType */) { return getTypeOfSymbolWithDeferredType(symbol); } - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + if (checkFlags & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 8192 /* ReverseMapped */) { + if (checkFlags & 262144 /* Mapped */) { + return getTypeOfMappedSymbol(symbol); + } + if (checkFlags & 8192 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -41920,7 +41951,7 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReturnTypeOfSignature(constructors[0]); + baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; @@ -41963,8 +41994,8 @@ var ts; } // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed? // There's no reason a `T` should be allowed while a `Readonly` should not. - return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType)); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -41973,7 +42004,7 @@ var ts; if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); + var baseType = getReducedType(getTypeFromTypeNode(node)); if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -43138,7 +43169,6 @@ var ts; // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); - var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (isTypeUsableAsPropertyName(t)) { @@ -43148,13 +43178,10 @@ var ts; !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); - var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); - // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the - // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks - // mode, if the underlying property is optional we remove 'undefined' from the type. - prop.type = strictNullChecks && isOptional && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : - propType; + var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */; + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0)); + prop.mappedType = type; + prop.mapper = templateMapper; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; prop.declarations = modifiersProp.declarations; @@ -43162,14 +43189,38 @@ var ts; prop.nameType = t; members.set(propName, prop); } - else if (t.flags & (1 /* Any */ | 4 /* String */)) { - stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); - } - else if (t.flags & (8 /* Number */ | 32 /* Enum */)) { - numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) { + var propType = instantiateType(templateType, templateMapper); + if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else { + numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } } } } + function getTypeOfMappedSymbol(symbol) { + if (!symbol.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType); + var propType = instantiateType(templateType, symbol.mapper); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : + symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (!popTypeResolution()) { + error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType)); + type = errorType; + } + symbol.type = type; + } + return symbol.type; + } function getTypeParameterFromMappedType(type) { return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); @@ -43304,7 +43355,7 @@ var ts; return type.resolvedProperties; } function getPropertiesOfType(type) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); @@ -43623,7 +43674,7 @@ var ts; /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the - * type itself. Note that the apparent type of a union type is the union type itself. + * type itself. */ function getApparentType(type) { var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; @@ -43651,7 +43702,7 @@ var ts; for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var current = _a[_i]; var type = getApparentType(current); - if (type !== errorType) { + if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { @@ -43723,6 +43774,9 @@ var ts; if (isLiteralType(type)) { checkFlags |= 128 /* HasLiteralType */; } + if (type.flags & 131072 /* Never */) { + checkFlags |= 131072 /* HasNeverType */; + } propTypes.push(type); } ts.addRange(propTypes, indexTypes); @@ -43769,6 +43823,41 @@ var ts; // We need to filter out partial properties in union types return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined; } + /** + * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types. + * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'. + * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when + * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. + */ + function getReducedType(type) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); + } + else if (type.flags & 2097152 /* Intersection */) { + if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + } + return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + } + return type; + } + function getReducedUnionType(unionType) { + var reducedTypes = ts.sameMap(unionType.types, getReducedType); + if (reducedTypes === unionType.types) { + return unionType; + } + var reduced = getUnionType(reducedTypes); + if (reduced.flags & 1048576 /* Union */) { + reduced.resolvedReducedType = reduced; + } + return reduced; + } + function isDiscriminantWithNeverType(prop) { + return !(prop.flags & 16777216 /* Optional */) && + (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && + !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -43778,7 +43867,7 @@ var ts; * @param name a name of property to look up in a given type */ function getPropertyOfType(type, name) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); @@ -43814,7 +43903,7 @@ var ts; * maps primitive types and type parameters are to their apparent types. */ function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); + return getSignaturesOfStructuredType(getApparentType(getReducedType(type)), kind); } function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 3670016 /* StructuredType */) { @@ -43829,12 +43918,12 @@ var ts; // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); + return getIndexInfoOfStructuredType(getApparentType(getReducedType(type)), kind); } // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); + return getIndexTypeOfStructuredType(getApparentType(getReducedType(type)), kind); } function getImplicitIndexTypeOfType(type, kind) { if (isObjectTypeWithInferableIndex(type)) { @@ -45116,14 +45205,14 @@ var ts; } // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; if (flags & 66846720 /* StructuredOrInstantiable */) includes |= 262144 /* IncludesStructuredOrInstantiable */; if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) - includes |= 2097152 /* IncludesNonWideningType */; + includes |= 4194304 /* IncludesNonWideningType */; } else { var len = typeSet.length; @@ -45229,7 +45318,7 @@ var ts; var includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */) { if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; + return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1 /* Literal */: @@ -45244,12 +45333,14 @@ var ts; break; } if (typeSet.length === 0) { - return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType : - includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : + return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -45321,15 +45412,15 @@ var ts; return addTypesToIntersection(typeSet, includes, type.types); } if (isEmptyAnonymousObjectType(type)) { - if (!(includes & 8388608 /* IncludesEmptyObject */)) { - includes |= 8388608 /* IncludesEmptyObject */; + if (!(includes & 16777216 /* IncludesEmptyObject */)) { + includes |= 16777216 /* IncludesEmptyObject */; typeSet.set(type.id.toString(), type); } } else { if (flags & 3 /* AnyOrUnknown */) { if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; } else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) { if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) { @@ -45339,7 +45430,7 @@ var ts; } typeSet.set(type.id.toString(), type); } - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; } return includes; } @@ -45472,7 +45563,7 @@ var ts; // a void-like type and a type known to be non-void-like, or // a non-primitive type and a type known to be primitive. if (includes & 131072 /* Never */ || - strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 8388608 /* IncludesEmptyObject */) || + strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) || includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || @@ -45482,7 +45573,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType; + return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType; } if (!strictNullChecks && includes & 98304 /* Nullable */) { return includes & 32768 /* Undefined */ ? undefinedType : nullType; @@ -45493,7 +45584,7 @@ var ts; includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { + if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { @@ -45598,6 +45689,7 @@ var ts; } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + type = getReducedType(type); return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : @@ -45987,7 +46079,7 @@ var ts; // In the following we resolve T[K] to the type of the property in T selected by K. // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. - var apparentObjectType = getApparentType(objectType); + var apparentObjectType = getApparentType(getReducedType(objectType)); if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; var wasMissingProp = false; @@ -46883,7 +46975,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { + return mapType(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { var replacementMapper = createReplacementMapper(typeVariable, t, mapper); return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) : @@ -47945,7 +48037,8 @@ var ts; } } else { - if (!(source.flags === target.flags && source.flags & 66584576 /* Substructure */)) + if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) && + source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */)) return false; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { @@ -47963,16 +48056,17 @@ var ts; return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { - do { + while (true) { var t = isFreshLiteralType(type) ? type.regularType : ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : - type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : - type; + type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) : + type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : + type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : + type; if (t === type) break; type = t; - } while (true); + } return type; } /** @@ -51121,6 +51215,7 @@ var ts; } } else { + source = getReducedType(source); if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. @@ -51743,9 +51838,6 @@ var ts; } return false; } - function isSyntheticThisPropertyAccess(expr) { - return ts.isAccessExpression(expr) && expr.expression.kind === 104 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */); - } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -52996,11 +53088,6 @@ var ts; if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { - return declaredType; - } return type; } if (type.flags & 1 /* Any */ && literal.text === "function") { @@ -53174,16 +53261,6 @@ var ts; if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' - // references might reference a different 'y' property. However, we make an exception - // for property accesses where x is a synthetic 'this' expression, indicating that we - // were called from isPropertyInitializedInConstructor. Without this exception, - // initializations of 'this' properties that occur before a 'this instanceof XXX' - // check would not be considered. - if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) { - return declaredType; - } return type; } // Check that right operand is a function type with a prototype property @@ -53256,9 +53333,6 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } } } return type; @@ -55217,7 +55291,7 @@ var ts; hasComputedStringProperty = false; hasComputedNumberProperty = false; } - var type = checkExpression(memberDecl.expression); + var type = getReducedType(checkExpression(memberDecl.expression)); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; @@ -55404,7 +55478,7 @@ var ts; spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -62228,15 +62302,14 @@ var ts; checkSignatureDeclaration(node); } function checkJSDocImplementsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); - return; } } function checkJSDocAugmentsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } @@ -64263,7 +64336,7 @@ var ts; } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); + var t = getReducedType(getTypeFromTypeNode(typeRefNode)); if (t !== errorType) { if (isValidBaseType(t)) { var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? @@ -73472,9 +73545,7 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) - ? target.expression - : target; + return target; } } ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; @@ -76643,7 +76714,7 @@ var ts; /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), /*type*/ undefined, iife) - ], languageVersion > 1 /* ES5 */ ? 2 /* Const */ : undefined)); + ], languageVersion > 1 /* ES5 */ ? 1 /* Let */ : undefined)); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); @@ -78382,9 +78453,11 @@ var ts; if (node.isTypeOnly) { return undefined; } - if (!node.exportClause) { - // Elide a star export if the module it references does not export a value. - return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) { + // never elide `export from ` declarations - + // they should be kept for sideffects/untyped exports, even when the + // type checker doesn't know about any exports + return node; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -107981,6 +108054,10 @@ var ts; : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); } ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsModules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); }); + } + ts.programContainsModules = programContainsModules; function programContainsEs6Modules(program) { return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); } @@ -108118,7 +108195,8 @@ var ts; } ts.findModifier = findModifier; function insertImport(changes, sourceFile, importDecl, blankLineBetween) { - var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var importKindPredicate = importDecl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; + var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); }); if (lastImportDeclaration) { changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); } @@ -111689,20 +111767,17 @@ var ts; filterGlobalCompletion(symbols); } function shouldOfferImportCompletions() { - // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs) + // If not already a module, must have modules enabled. if (!preferences.includeCompletionsForModuleExports) return false; // If already using ES6 modules, OK to continue using them. - if (sourceFile.externalModuleIndicator) + if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; - // If already using commonjs, don't introduce ES6. - if (sourceFile.commonJsModuleIndicator) - return false; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) return true; // If some file is using ES6 modules, assume that it's OK to add more. - return ts.programContainsEs6Modules(program); + return ts.programContainsModules(program); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { @@ -111845,6 +111920,7 @@ var ts; var startTime = ts.timestamp(); log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : "")); var seenResolvedModules = ts.createMap(); + var seenExports = ts.createMap(); /** Bucket B */ var aliasesToAlreadyIncludedSymbols = ts.createMap(); /** Bucket C */ @@ -111865,17 +111941,20 @@ var ts; } // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { + if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, isNonGlobalDeclaration)) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } - for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; + var symbolId = ts.getSymbolId(symbol).toString(); + // `getExportsAndPropertiesOfModule` can include duplicates + if (!ts.addToSeen(seenExports, symbolId)) { + continue; + } // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) { continue; } - var symbolId = ts.getSymbolId(symbol).toString(); // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol; // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). @@ -112859,6 +112938,15 @@ var ts; } } } + function isNonGlobalDeclaration(declaration) { + var sourceFile = declaration.getSourceFile(); + // If the file is not a module, the declaration is global + if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { + return false; + } + // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation + return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -128904,7 +128992,8 @@ var ts; var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker)); var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, sourceFile, compilerOptions, checker, program.getSourceFiles()); var preferTypeOnlyImport = !!usageIsTypeOnly && compilerOptions.importsNotUsedAsValues === 2 /* Error */; - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, host, preferences); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, useRequire, host, preferences); addImport({ fixes: [fix], symbolName: symbolName }); } function addImport(info) { @@ -128918,11 +129007,11 @@ var ts; importType.push(fix); break; case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - var key = String(ts.getNodeId(importClause)); + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; + var key = String(ts.getNodeId(importClauseOrBindingPattern)); var entry = addToExisting.get(key); if (!entry) { - addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); + addToExisting.set(key, entry = { importClauseOrBindingPattern: importClauseOrBindingPattern, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); } if (importKind === 0 /* Named */) { ts.pushIfUnique(entry.namedImports, symbolName); @@ -128934,10 +129023,10 @@ var ts; break; } case 3 /* AddNew */: { - var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, typeOnly = fix.typeOnly; + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, useRequire = fix.useRequire, typeOnly = fix.typeOnly; var entry = newImports.get(moduleSpecifier); if (!entry) { - newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly }); + newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire }); lastModuleSpecifier = moduleSpecifier; } else { @@ -128950,9 +129039,9 @@ var ts; entry.defaultImport = symbolName; break; case 0 /* Named */: - ts.pushIfUnique(entry.namedImports, symbolName); + ts.pushIfUnique(entry.namedImports || (entry.namedImports = []), symbolName); break; - case 3 /* Equals */: + case 3 /* CommonJS */: case 2 /* Namespace */: ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName, "Namespacelike import shoudl be missing or match symbolName"); entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; @@ -128975,11 +129064,13 @@ var ts; addImportType(changeTracker, sourceFile, fix, quotePreference); } addToExisting.forEach(function (_a) { - var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; - doAddExistingFix(changeTracker, sourceFile, importClause, defaultImport, namedImports, canUseTypeOnlyImport); + var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; + doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport); }); - newImports.forEach(function (imports, moduleSpecifier) { - addNewImports(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); + newImports.forEach(function (_a, moduleSpecifier) { + var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]); + var addDeclarations = useRequire ? addNewRequires : addNewImports; + addDeclarations(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); }); } } @@ -128997,22 +129088,22 @@ var ts; ImportKind[ImportKind["Named"] = 0] = "Named"; ImportKind[ImportKind["Default"] = 1] = "Default"; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["Equals"] = 3] = "Equals"; - ImportKind[ImportKind["ConstEquals"] = 4] = "ConstEquals"; + ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, sourceFile, compilerOptions, program.getTypeChecker(), program.getSourceFiles()); - var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, exportInfos, host, preferences)).moduleSpecifier; - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, host, preferences); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, host, preferences) { + function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, program, sourceFile, host, preferences)); + return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -129029,7 +129120,7 @@ var ts; if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); } - for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); @@ -129046,13 +129137,13 @@ var ts; } function getFixForImport(exportInfos, symbolName, /** undefined only for missing JSX namespace */ - position, preferTypeOnlyImport, program, sourceFile, host, preferences) { + position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. - var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, host, preferences); + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences); return __spreadArrays((useNamespace ? [useNamespace] : ts.emptyArray), addImport); } function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { @@ -129070,58 +129161,91 @@ var ts; // and it is up to the user to decide which one fits best. return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + var namespacePrefix = getNamespaceLikeImportText(declaration); + if (namespacePrefix) { + var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position }; } } }); } + function getTargetModuleFromNamespaceLikeImport(declaration, checker) { + var _a; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); + case 253 /* ImportEqualsDeclaration */: + return checker.getAliasedSymbol(declaration.symbol); + case 254 /* ImportDeclaration */: + var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); + return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); + default: + return ts.Debug.assertNever(declaration); + } + } + function getNamespaceLikeImportText(declaration) { + var _a, _b, _c; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; + case 253 /* ImportEqualsDeclaration */: + return declaration.name.text; + case 254 /* ImportDeclaration */: + return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; + default: + return ts.Debug.assertNever(declaration); + } + } function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind !== 254 /* ImportDeclaration */) + if (declaration.kind === 253 /* ImportEqualsDeclaration */) return undefined; + if (declaration.kind === 242 /* VariableDeclaration */) { + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 189 /* ObjectBindingPattern */ + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false } + : undefined; + } var importClause = declaration.importClause; if (!importClause) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 257 /* NamedImports */) - ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind, canUseTypeOnlyImport: canUseTypeOnlyImport } + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; }); } - function getNamespaceImportName(declaration) { - if (declaration.kind === 254 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 256 /* NamespaceImport */ ? namedBindings.name : undefined; - } - else { - return declaration.name; - } - } function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) - && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, exportedSymbolIsTypeOnly: exportedSymbolIsTypeOnly } : undefined; + if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined; + } + if (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) { + return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + } }); } - function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, moduleSymbols, host, preferences) { + function shouldUseRequire(sourceFile, compilerOptions) { + return ts.isSourceFileJS(sourceFile) + && !sourceFile.externalModuleIndicator + && (!!sourceFile.commonJsModuleIndicator || ts.getEmitModuleKind(compilerOptions) < ts.ModuleKind.ES2015); + } + function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); + var compilerOptions = program.getCompilerOptions(); var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, compilerOptions, sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.checkDefined(position, "position should be defined") } - : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, typeOnly: preferTypeOnlyImport }; + : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; }); }); // Sort by presence in package.json, then shortest paths first @@ -129137,19 +129261,18 @@ var ts; return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } - function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, host, preferences) { - var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport); }); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, exportInfos, host, preferences); + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } - function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport) { + function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 254 /* ImportDeclaration */ - ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 265 /* ExternalModuleReference */ - ? declaration.moduleReference.expression - : undefined; - return expression && ts.isStringLiteral(expression) - ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind, typeOnly: preferTypeOnlyImport } + var moduleSpecifier = declaration.kind === 254 /* ImportDeclaration */ ? declaration.moduleSpecifier : + declaration.kind === 242 /* VariableDeclaration */ ? declaration.initializer.arguments[0] : + declaration.moduleReference.kind === 265 /* ExternalModuleReference */ ? declaration.moduleReference.expression : + undefined; + return moduleSpecifier && ts.isStringLiteral(moduleSpecifier) + ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } : undefined; } function getFixesInfo(context, errorCode, pos) { @@ -129168,7 +129291,8 @@ var ts; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; - var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, program, sourceFile, host, preferences); + var useRequire = shouldUseRequire(sourceFile, program.getCompilerOptions()); + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -129194,9 +129318,9 @@ var ts; case ts.ModuleKind.CommonJS: case ts.ModuleKind.UMD: if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 3 /* CommonJS */; } - return 3 /* Equals */; + return 3 /* CommonJS */; case ts.ModuleKind.System: case ts.ModuleKind.ES2015: case ts.ModuleKind.ES2020: @@ -129219,11 +129343,13 @@ var ts; : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); - var preferTypeOnlyImport = program.getCompilerOptions().importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); + var compilerOptions = program.getCompilerOptions(); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program, host); var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, program, sourceFile, host, preferences); + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } @@ -129274,7 +129400,7 @@ var ts; // 2. 'import =' will not work in JavaScript, so the decision is between a default // and const/require. if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 1 /* Default */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 1 /* Default */ : 3 /* CommonJS */; } // 3. At this point the most correct choice is probably 'import =', but people // really hate that, so look to see if the importing file has any precedent @@ -129282,12 +129408,12 @@ var ts; for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (ts.isImportEqualsDeclaration(statement)) { - return 3 /* Equals */; + return 3 /* CommonJS */; } } // 4. We have no precedent to go on, so just use a default import if // allowSyntheticDefaultImports/esModuleInterop is enabled. - return allowSyntheticDefaults ? 1 /* Default */ : 3 /* Equals */; + return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); @@ -129335,16 +129461,18 @@ var ts; addImportType(changes, sourceFile, fix, quotePreference); return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport, moduleSpecifier = fix.moduleSpecifier; + doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! } case 3 /* AddNew */: { - var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly; - addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined, typeOnly: typeOnly } - : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined, typeOnly: typeOnly } - : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }, /*blankLineBetween*/ true); + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire; + var addDeclarations = useRequire ? addNewRequires : addNewImports; + var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } : + importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } : + { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }; + addDeclarations(changes, sourceFile, moduleSpecifier, quotePreference, importsCollection, /*blankLineBetween*/ true); return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: @@ -129352,6 +129480,16 @@ var ts; } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) { + if (clause.kind === 189 /* ObjectBindingPattern */) { + if (defaultImport) { + addElementToBindingPattern(clause, defaultImport, "default"); + } + for (var _i = 0, namedImports_1 = namedImports; _i < namedImports_1.length; _i++) { + var specifier = namedImports_1[_i]; + addElementToBindingPattern(clause, specifier, /*propertyName*/ undefined); + } + return; + } var convertTypeOnlyToRegular = !canUseTypeOnlyImport && clause.isTypeOnly; if (defaultImport) { ts.Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one"); @@ -129360,19 +129498,19 @@ var ts; if (namedImports.length) { var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { - for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { - var spec = specifiers_1[_i]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var spec = specifiers_1[_a]; changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); } } else { if (specifiers.length) { - var namedImports_1 = ts.createNamedImports(specifiers); + var namedImports_2 = ts.createNamedImports(specifiers); if (clause.namedBindings) { - changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_2); } else { - changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_1); + changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_2); } } } @@ -129380,6 +129518,15 @@ var ts; if (convertTypeOnlyToRegular) { changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(clause, sourceFile)); } + function addElementToBindingPattern(bindingPattern, name, propertyName) { + var element = ts.createBindingElement(/*dotDotDotToken*/ undefined, propertyName, name); + if (bindingPattern.elements.length) { + changes.insertNodeInListAfter(sourceFile, ts.last(bindingPattern.elements), element); + } + else { + changes.replaceNode(sourceFile, bindingPattern, ts.createObjectBindingPattern([element])); + } + } } function addNamespaceQualifier(changes, sourceFile, _a) { var namespacePrefix = _a.namespacePrefix, position = _a.position; @@ -129393,21 +129540,47 @@ var ts; var quote = ts.getQuoteFromPreference(quotePreference); return "import(" + quote + moduleSpecifier + quote + ")."; } - function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a, blankLineBetween) { - var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport, typeOnly = _a.typeOnly; + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); - if (defaultImport !== undefined || namedImports.length) { - ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, typeOnly), /*blankLineBetween*/ blankLineBetween); + if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + ts.insertImport(changes, sourceFile, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly), /*blankLineBetween*/ blankLineBetween); } + var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly; if (namespaceLikeImport) { - ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) : - namespaceLikeImport.importKind === 4 /* ConstEquals */ ? createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier) : - ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier), /*blankLineBetween*/ blankLineBetween); + var declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ + ? ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause( + /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, /*blankLineBetween*/ blankLineBetween); + } + } + function addNewRequires(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + var _a, _b; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + // const { default: foo, bar, etc } = require('./mod'); + if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || []; + if (imports.defaultImport) { + bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport)); + } + var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + } + // const foo = require('./mod'); + if (imports.namespaceLikeImport) { + var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, blankLineBetween); } } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.createIdentifier(name), + return ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(typeof name === "string" ? ts.createIdentifier(name) : name, /*type*/ undefined, ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier])) ], 2 /* Const */)); } @@ -135831,7 +136004,7 @@ var ts; get: function () { return ts.symbolName(this); }, - enumerable: true, + enumerable: false, configurable: true }); SymbolObject.prototype.getEscapedName = function () { @@ -135878,7 +136051,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return IdentifierObject; @@ -135893,7 +136066,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return PrivateIdentifierObject; @@ -135986,7 +136159,7 @@ var ts; } return undefined; }, - enumerable: true, + enumerable: false, configurable: true }); return TypeObject; @@ -140269,7 +140442,7 @@ var ts; get: function () { return this.projectService.typingsCache; }, - enumerable: true, + enumerable: false, configurable: true }); /*@internal*/ @@ -147215,7 +147388,7 @@ var ts; } Object.defineProperty(EditWalker.prototype, "done", { get: function () { return false; }, - enumerable: true, + enumerable: false, configurable: true }); EditWalker.prototype.insertLines = function (insertedText, suppressTrailingText) { diff --git a/lib/typescript.js b/lib/typescript.js index 071b8dcad99..e88bb827fd1 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -3920,6 +3920,9 @@ var ts; CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter"; CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter"; CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType"; + CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType"; + CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped"; + CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant"; CheckFlags[CheckFlags["Partial"] = 48] = "Partial"; @@ -4046,16 +4049,16 @@ var ts; TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ - TypeFlags[TypeFlags["IncludesMask"] = 68943871] = "IncludesMask"; + TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask"; // The following flags are used for different purposes during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable"; /* @internal */ - TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType"; + TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType"; /* @internal */ - TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard"; + TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ - TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject"; + TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -4097,6 +4100,12 @@ var ts; ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; /* @internal */ ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; @@ -7340,6 +7349,7 @@ var ts; Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), + Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -14516,6 +14526,15 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; + function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument); + } + ts.isRequireVariableDeclaration = isRequireVariableDeclaration; + function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) { + if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + } + ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement; function isSingleOrDoubleQuote(charCode) { return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } @@ -15094,19 +15113,22 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - return getHostSignatureFromJSDocHost(getJSDocHost(node)); + var host = getEffectiveJSDocHost(node); + return host && ts.isFunctionLike(host) ? host : undefined; } ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; - function getHostSignatureFromJSDocHost(host) { + function getEffectiveJSDocHost(node) { + var host = getJSDocHost(node); var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || host; - return decl && ts.isFunctionLike(decl) ? decl : undefined; + return decl; } - ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + ts.getEffectiveJSDocHost = getEffectiveJSDocHost; + /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */ function getJSDocHost(node) { return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent; } @@ -34951,6 +34973,9 @@ var ts; getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleName: function (moduleSpecifier) { + return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); + }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, tryGetThisTypeAt: function (node, includeGlobalThis) { node = ts.getParseTreeNode(node); @@ -36736,7 +36761,7 @@ var ts; return resolved; } function getTargetOfExportAssignment(node, dontResolveAlias) { - var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + var expression = ts.isExportAssignment(node) ? node.expression : node.right; var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); return resolved; @@ -37044,8 +37069,8 @@ var ts; return getDeclarationOfJSPrototypeContainer(symbol); } } - var sig = ts.getHostSignatureFromJSDocHost(host); - if (sig) { + var sig = ts.getEffectiveJSDocHost(node); + if (sig && ts.isFunctionLike(sig)) { var symbol = getSymbolOfNode(sig); return symbol && symbol.valueDeclaration; } @@ -38107,6 +38132,7 @@ var ts; context.encounteredError = true; return undefined; // TODO: GH#18217 } + type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -39960,7 +39986,7 @@ var ts; var varName = getUnusedName(name, symbol); // We have to use `getWidenedType` here since the object within a json file is unwidened within the file // (Unwidened types can only exist in expression contexts and should never be serialized) - var typeToSerialize = getWidenedType(getTypeOfSymbol(symbol)); + var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol))); if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) { // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */); @@ -40815,6 +40841,7 @@ var ts; var type; if (pattern.kind === 189 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { + parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; @@ -41626,13 +41653,17 @@ var ts; return links.type; } function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 65536 /* DeferredType */) { + var checkFlags = ts.getCheckFlags(symbol); + if (checkFlags & 65536 /* DeferredType */) { return getTypeOfSymbolWithDeferredType(symbol); } - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + if (checkFlags & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 8192 /* ReverseMapped */) { + if (checkFlags & 262144 /* Mapped */) { + return getTypeOfMappedSymbol(symbol); + } + if (checkFlags & 8192 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -41920,7 +41951,7 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReturnTypeOfSignature(constructors[0]); + baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; @@ -41963,8 +41994,8 @@ var ts; } // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed? // There's no reason a `T` should be allowed while a `Readonly` should not. - return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType)); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -41973,7 +42004,7 @@ var ts; if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); + var baseType = getReducedType(getTypeFromTypeNode(node)); if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -43138,7 +43169,6 @@ var ts; // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); - var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (isTypeUsableAsPropertyName(t)) { @@ -43148,13 +43178,10 @@ var ts; !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); - var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); - // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the - // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks - // mode, if the underlying property is optional we remove 'undefined' from the type. - prop.type = strictNullChecks && isOptional && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : - propType; + var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */; + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0)); + prop.mappedType = type; + prop.mapper = templateMapper; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; prop.declarations = modifiersProp.declarations; @@ -43162,14 +43189,38 @@ var ts; prop.nameType = t; members.set(propName, prop); } - else if (t.flags & (1 /* Any */ | 4 /* String */)) { - stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); - } - else if (t.flags & (8 /* Number */ | 32 /* Enum */)) { - numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) { + var propType = instantiateType(templateType, templateMapper); + if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else { + numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } } } } + function getTypeOfMappedSymbol(symbol) { + if (!symbol.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType); + var propType = instantiateType(templateType, symbol.mapper); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : + symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (!popTypeResolution()) { + error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType)); + type = errorType; + } + symbol.type = type; + } + return symbol.type; + } function getTypeParameterFromMappedType(type) { return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); @@ -43304,7 +43355,7 @@ var ts; return type.resolvedProperties; } function getPropertiesOfType(type) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); @@ -43623,7 +43674,7 @@ var ts; /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the - * type itself. Note that the apparent type of a union type is the union type itself. + * type itself. */ function getApparentType(type) { var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; @@ -43651,7 +43702,7 @@ var ts; for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var current = _a[_i]; var type = getApparentType(current); - if (type !== errorType) { + if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { @@ -43723,6 +43774,9 @@ var ts; if (isLiteralType(type)) { checkFlags |= 128 /* HasLiteralType */; } + if (type.flags & 131072 /* Never */) { + checkFlags |= 131072 /* HasNeverType */; + } propTypes.push(type); } ts.addRange(propTypes, indexTypes); @@ -43769,6 +43823,41 @@ var ts; // We need to filter out partial properties in union types return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined; } + /** + * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types. + * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'. + * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when + * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. + */ + function getReducedType(type) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); + } + else if (type.flags & 2097152 /* Intersection */) { + if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + } + return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + } + return type; + } + function getReducedUnionType(unionType) { + var reducedTypes = ts.sameMap(unionType.types, getReducedType); + if (reducedTypes === unionType.types) { + return unionType; + } + var reduced = getUnionType(reducedTypes); + if (reduced.flags & 1048576 /* Union */) { + reduced.resolvedReducedType = reduced; + } + return reduced; + } + function isDiscriminantWithNeverType(prop) { + return !(prop.flags & 16777216 /* Optional */) && + (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && + !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -43778,7 +43867,7 @@ var ts; * @param name a name of property to look up in a given type */ function getPropertyOfType(type, name) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); @@ -43814,7 +43903,7 @@ var ts; * maps primitive types and type parameters are to their apparent types. */ function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); + return getSignaturesOfStructuredType(getApparentType(getReducedType(type)), kind); } function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 3670016 /* StructuredType */) { @@ -43829,12 +43918,12 @@ var ts; // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); + return getIndexInfoOfStructuredType(getApparentType(getReducedType(type)), kind); } // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); + return getIndexTypeOfStructuredType(getApparentType(getReducedType(type)), kind); } function getImplicitIndexTypeOfType(type, kind) { if (isObjectTypeWithInferableIndex(type)) { @@ -45116,14 +45205,14 @@ var ts; } // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; if (flags & 66846720 /* StructuredOrInstantiable */) includes |= 262144 /* IncludesStructuredOrInstantiable */; if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) - includes |= 2097152 /* IncludesNonWideningType */; + includes |= 4194304 /* IncludesNonWideningType */; } else { var len = typeSet.length; @@ -45229,7 +45318,7 @@ var ts; var includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */) { if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; + return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1 /* Literal */: @@ -45244,12 +45333,14 @@ var ts; break; } if (typeSet.length === 0) { - return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType : - includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : + return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -45321,15 +45412,15 @@ var ts; return addTypesToIntersection(typeSet, includes, type.types); } if (isEmptyAnonymousObjectType(type)) { - if (!(includes & 8388608 /* IncludesEmptyObject */)) { - includes |= 8388608 /* IncludesEmptyObject */; + if (!(includes & 16777216 /* IncludesEmptyObject */)) { + includes |= 16777216 /* IncludesEmptyObject */; typeSet.set(type.id.toString(), type); } } else { if (flags & 3 /* AnyOrUnknown */) { if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; } else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) { if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) { @@ -45339,7 +45430,7 @@ var ts; } typeSet.set(type.id.toString(), type); } - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; } return includes; } @@ -45472,7 +45563,7 @@ var ts; // a void-like type and a type known to be non-void-like, or // a non-primitive type and a type known to be primitive. if (includes & 131072 /* Never */ || - strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 8388608 /* IncludesEmptyObject */) || + strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) || includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || @@ -45482,7 +45573,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType; + return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType; } if (!strictNullChecks && includes & 98304 /* Nullable */) { return includes & 32768 /* Undefined */ ? undefinedType : nullType; @@ -45493,7 +45584,7 @@ var ts; includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { + if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { @@ -45598,6 +45689,7 @@ var ts; } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + type = getReducedType(type); return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : @@ -45987,7 +46079,7 @@ var ts; // In the following we resolve T[K] to the type of the property in T selected by K. // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. - var apparentObjectType = getApparentType(objectType); + var apparentObjectType = getApparentType(getReducedType(objectType)); if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; var wasMissingProp = false; @@ -46883,7 +46975,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { + return mapType(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { var replacementMapper = createReplacementMapper(typeVariable, t, mapper); return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) : @@ -47945,7 +48037,8 @@ var ts; } } else { - if (!(source.flags === target.flags && source.flags & 66584576 /* Substructure */)) + if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) && + source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */)) return false; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { @@ -47963,16 +48056,17 @@ var ts; return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { - do { + while (true) { var t = isFreshLiteralType(type) ? type.regularType : ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : - type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : - type; + type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) : + type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : + type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : + type; if (t === type) break; type = t; - } while (true); + } return type; } /** @@ -51121,6 +51215,7 @@ var ts; } } else { + source = getReducedType(source); if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. @@ -51743,9 +51838,6 @@ var ts; } return false; } - function isSyntheticThisPropertyAccess(expr) { - return ts.isAccessExpression(expr) && expr.expression.kind === 104 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */); - } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -52996,11 +53088,6 @@ var ts; if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { - return declaredType; - } return type; } if (type.flags & 1 /* Any */ && literal.text === "function") { @@ -53174,16 +53261,6 @@ var ts; if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' - // references might reference a different 'y' property. However, we make an exception - // for property accesses where x is a synthetic 'this' expression, indicating that we - // were called from isPropertyInitializedInConstructor. Without this exception, - // initializations of 'this' properties that occur before a 'this instanceof XXX' - // check would not be considered. - if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) { - return declaredType; - } return type; } // Check that right operand is a function type with a prototype property @@ -53256,9 +53333,6 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } } } return type; @@ -55217,7 +55291,7 @@ var ts; hasComputedStringProperty = false; hasComputedNumberProperty = false; } - var type = checkExpression(memberDecl.expression); + var type = getReducedType(checkExpression(memberDecl.expression)); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; @@ -55404,7 +55478,7 @@ var ts; spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -62228,15 +62302,14 @@ var ts; checkSignatureDeclaration(node); } function checkJSDocImplementsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); - return; } } function checkJSDocAugmentsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } @@ -64263,7 +64336,7 @@ var ts; } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); + var t = getReducedType(getTypeFromTypeNode(typeRefNode)); if (t !== errorType) { if (isValidBaseType(t)) { var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? @@ -73472,9 +73545,7 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) - ? target.expression - : target; + return target; } } ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; @@ -76643,7 +76714,7 @@ var ts; /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), /*type*/ undefined, iife) - ], languageVersion > 1 /* ES5 */ ? 2 /* Const */ : undefined)); + ], languageVersion > 1 /* ES5 */ ? 1 /* Let */ : undefined)); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); @@ -78382,9 +78453,11 @@ var ts; if (node.isTypeOnly) { return undefined; } - if (!node.exportClause) { - // Elide a star export if the module it references does not export a value. - return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) { + // never elide `export from ` declarations - + // they should be kept for sideffects/untyped exports, even when the + // type checker doesn't know about any exports + return node; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -107981,6 +108054,10 @@ var ts; : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); } ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsModules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); }); + } + ts.programContainsModules = programContainsModules; function programContainsEs6Modules(program) { return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); } @@ -108118,7 +108195,8 @@ var ts; } ts.findModifier = findModifier; function insertImport(changes, sourceFile, importDecl, blankLineBetween) { - var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var importKindPredicate = importDecl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; + var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); }); if (lastImportDeclaration) { changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); } @@ -111689,20 +111767,17 @@ var ts; filterGlobalCompletion(symbols); } function shouldOfferImportCompletions() { - // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs) + // If not already a module, must have modules enabled. if (!preferences.includeCompletionsForModuleExports) return false; // If already using ES6 modules, OK to continue using them. - if (sourceFile.externalModuleIndicator) + if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; - // If already using commonjs, don't introduce ES6. - if (sourceFile.commonJsModuleIndicator) - return false; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) return true; // If some file is using ES6 modules, assume that it's OK to add more. - return ts.programContainsEs6Modules(program); + return ts.programContainsModules(program); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { @@ -111845,6 +111920,7 @@ var ts; var startTime = ts.timestamp(); log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : "")); var seenResolvedModules = ts.createMap(); + var seenExports = ts.createMap(); /** Bucket B */ var aliasesToAlreadyIncludedSymbols = ts.createMap(); /** Bucket C */ @@ -111865,17 +111941,20 @@ var ts; } // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { + if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, isNonGlobalDeclaration)) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } - for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; + var symbolId = ts.getSymbolId(symbol).toString(); + // `getExportsAndPropertiesOfModule` can include duplicates + if (!ts.addToSeen(seenExports, symbolId)) { + continue; + } // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) { continue; } - var symbolId = ts.getSymbolId(symbol).toString(); // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol; // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). @@ -112859,6 +112938,15 @@ var ts; } } } + function isNonGlobalDeclaration(declaration) { + var sourceFile = declaration.getSourceFile(); + // If the file is not a module, the declaration is global + if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { + return false; + } + // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation + return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -128904,7 +128992,8 @@ var ts; var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker)); var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, sourceFile, compilerOptions, checker, program.getSourceFiles()); var preferTypeOnlyImport = !!usageIsTypeOnly && compilerOptions.importsNotUsedAsValues === 2 /* Error */; - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, host, preferences); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, useRequire, host, preferences); addImport({ fixes: [fix], symbolName: symbolName }); } function addImport(info) { @@ -128918,11 +129007,11 @@ var ts; importType.push(fix); break; case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - var key = String(ts.getNodeId(importClause)); + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; + var key = String(ts.getNodeId(importClauseOrBindingPattern)); var entry = addToExisting.get(key); if (!entry) { - addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); + addToExisting.set(key, entry = { importClauseOrBindingPattern: importClauseOrBindingPattern, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); } if (importKind === 0 /* Named */) { ts.pushIfUnique(entry.namedImports, symbolName); @@ -128934,10 +129023,10 @@ var ts; break; } case 3 /* AddNew */: { - var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, typeOnly = fix.typeOnly; + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, useRequire = fix.useRequire, typeOnly = fix.typeOnly; var entry = newImports.get(moduleSpecifier); if (!entry) { - newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly }); + newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire }); lastModuleSpecifier = moduleSpecifier; } else { @@ -128950,9 +129039,9 @@ var ts; entry.defaultImport = symbolName; break; case 0 /* Named */: - ts.pushIfUnique(entry.namedImports, symbolName); + ts.pushIfUnique(entry.namedImports || (entry.namedImports = []), symbolName); break; - case 3 /* Equals */: + case 3 /* CommonJS */: case 2 /* Namespace */: ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName, "Namespacelike import shoudl be missing or match symbolName"); entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; @@ -128975,11 +129064,13 @@ var ts; addImportType(changeTracker, sourceFile, fix, quotePreference); } addToExisting.forEach(function (_a) { - var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; - doAddExistingFix(changeTracker, sourceFile, importClause, defaultImport, namedImports, canUseTypeOnlyImport); + var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; + doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport); }); - newImports.forEach(function (imports, moduleSpecifier) { - addNewImports(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); + newImports.forEach(function (_a, moduleSpecifier) { + var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]); + var addDeclarations = useRequire ? addNewRequires : addNewImports; + addDeclarations(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); }); } } @@ -128997,22 +129088,22 @@ var ts; ImportKind[ImportKind["Named"] = 0] = "Named"; ImportKind[ImportKind["Default"] = 1] = "Default"; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["Equals"] = 3] = "Equals"; - ImportKind[ImportKind["ConstEquals"] = 4] = "ConstEquals"; + ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, sourceFile, compilerOptions, program.getTypeChecker(), program.getSourceFiles()); - var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, exportInfos, host, preferences)).moduleSpecifier; - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, host, preferences); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, host, preferences) { + function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, program, sourceFile, host, preferences)); + return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -129029,7 +129120,7 @@ var ts; if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); } - for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); @@ -129046,13 +129137,13 @@ var ts; } function getFixForImport(exportInfos, symbolName, /** undefined only for missing JSX namespace */ - position, preferTypeOnlyImport, program, sourceFile, host, preferences) { + position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. - var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, host, preferences); + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences); return __spreadArrays((useNamespace ? [useNamespace] : ts.emptyArray), addImport); } function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { @@ -129070,58 +129161,91 @@ var ts; // and it is up to the user to decide which one fits best. return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + var namespacePrefix = getNamespaceLikeImportText(declaration); + if (namespacePrefix) { + var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position }; } } }); } + function getTargetModuleFromNamespaceLikeImport(declaration, checker) { + var _a; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); + case 253 /* ImportEqualsDeclaration */: + return checker.getAliasedSymbol(declaration.symbol); + case 254 /* ImportDeclaration */: + var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); + return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); + default: + return ts.Debug.assertNever(declaration); + } + } + function getNamespaceLikeImportText(declaration) { + var _a, _b, _c; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; + case 253 /* ImportEqualsDeclaration */: + return declaration.name.text; + case 254 /* ImportDeclaration */: + return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; + default: + return ts.Debug.assertNever(declaration); + } + } function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind !== 254 /* ImportDeclaration */) + if (declaration.kind === 253 /* ImportEqualsDeclaration */) return undefined; + if (declaration.kind === 242 /* VariableDeclaration */) { + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 189 /* ObjectBindingPattern */ + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false } + : undefined; + } var importClause = declaration.importClause; if (!importClause) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 257 /* NamedImports */) - ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind, canUseTypeOnlyImport: canUseTypeOnlyImport } + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; }); } - function getNamespaceImportName(declaration) { - if (declaration.kind === 254 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 256 /* NamespaceImport */ ? namedBindings.name : undefined; - } - else { - return declaration.name; - } - } function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) - && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, exportedSymbolIsTypeOnly: exportedSymbolIsTypeOnly } : undefined; + if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined; + } + if (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) { + return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + } }); } - function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, moduleSymbols, host, preferences) { + function shouldUseRequire(sourceFile, compilerOptions) { + return ts.isSourceFileJS(sourceFile) + && !sourceFile.externalModuleIndicator + && (!!sourceFile.commonJsModuleIndicator || ts.getEmitModuleKind(compilerOptions) < ts.ModuleKind.ES2015); + } + function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); + var compilerOptions = program.getCompilerOptions(); var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, compilerOptions, sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.checkDefined(position, "position should be defined") } - : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, typeOnly: preferTypeOnlyImport }; + : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; }); }); // Sort by presence in package.json, then shortest paths first @@ -129137,19 +129261,18 @@ var ts; return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } - function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, host, preferences) { - var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport); }); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, exportInfos, host, preferences); + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } - function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport) { + function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 254 /* ImportDeclaration */ - ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 265 /* ExternalModuleReference */ - ? declaration.moduleReference.expression - : undefined; - return expression && ts.isStringLiteral(expression) - ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind, typeOnly: preferTypeOnlyImport } + var moduleSpecifier = declaration.kind === 254 /* ImportDeclaration */ ? declaration.moduleSpecifier : + declaration.kind === 242 /* VariableDeclaration */ ? declaration.initializer.arguments[0] : + declaration.moduleReference.kind === 265 /* ExternalModuleReference */ ? declaration.moduleReference.expression : + undefined; + return moduleSpecifier && ts.isStringLiteral(moduleSpecifier) + ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } : undefined; } function getFixesInfo(context, errorCode, pos) { @@ -129168,7 +129291,8 @@ var ts; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; - var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, program, sourceFile, host, preferences); + var useRequire = shouldUseRequire(sourceFile, program.getCompilerOptions()); + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -129194,9 +129318,9 @@ var ts; case ts.ModuleKind.CommonJS: case ts.ModuleKind.UMD: if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 3 /* CommonJS */; } - return 3 /* Equals */; + return 3 /* CommonJS */; case ts.ModuleKind.System: case ts.ModuleKind.ES2015: case ts.ModuleKind.ES2020: @@ -129219,11 +129343,13 @@ var ts; : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); - var preferTypeOnlyImport = program.getCompilerOptions().importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); + var compilerOptions = program.getCompilerOptions(); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program, host); var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, program, sourceFile, host, preferences); + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } @@ -129274,7 +129400,7 @@ var ts; // 2. 'import =' will not work in JavaScript, so the decision is between a default // and const/require. if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 1 /* Default */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 1 /* Default */ : 3 /* CommonJS */; } // 3. At this point the most correct choice is probably 'import =', but people // really hate that, so look to see if the importing file has any precedent @@ -129282,12 +129408,12 @@ var ts; for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (ts.isImportEqualsDeclaration(statement)) { - return 3 /* Equals */; + return 3 /* CommonJS */; } } // 4. We have no precedent to go on, so just use a default import if // allowSyntheticDefaultImports/esModuleInterop is enabled. - return allowSyntheticDefaults ? 1 /* Default */ : 3 /* Equals */; + return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); @@ -129335,16 +129461,18 @@ var ts; addImportType(changes, sourceFile, fix, quotePreference); return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport, moduleSpecifier = fix.moduleSpecifier; + doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! } case 3 /* AddNew */: { - var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly; - addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined, typeOnly: typeOnly } - : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined, typeOnly: typeOnly } - : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }, /*blankLineBetween*/ true); + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire; + var addDeclarations = useRequire ? addNewRequires : addNewImports; + var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } : + importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } : + { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }; + addDeclarations(changes, sourceFile, moduleSpecifier, quotePreference, importsCollection, /*blankLineBetween*/ true); return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: @@ -129352,6 +129480,16 @@ var ts; } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) { + if (clause.kind === 189 /* ObjectBindingPattern */) { + if (defaultImport) { + addElementToBindingPattern(clause, defaultImport, "default"); + } + for (var _i = 0, namedImports_1 = namedImports; _i < namedImports_1.length; _i++) { + var specifier = namedImports_1[_i]; + addElementToBindingPattern(clause, specifier, /*propertyName*/ undefined); + } + return; + } var convertTypeOnlyToRegular = !canUseTypeOnlyImport && clause.isTypeOnly; if (defaultImport) { ts.Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one"); @@ -129360,19 +129498,19 @@ var ts; if (namedImports.length) { var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { - for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { - var spec = specifiers_1[_i]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var spec = specifiers_1[_a]; changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); } } else { if (specifiers.length) { - var namedImports_1 = ts.createNamedImports(specifiers); + var namedImports_2 = ts.createNamedImports(specifiers); if (clause.namedBindings) { - changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_2); } else { - changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_1); + changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_2); } } } @@ -129380,6 +129518,15 @@ var ts; if (convertTypeOnlyToRegular) { changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(clause, sourceFile)); } + function addElementToBindingPattern(bindingPattern, name, propertyName) { + var element = ts.createBindingElement(/*dotDotDotToken*/ undefined, propertyName, name); + if (bindingPattern.elements.length) { + changes.insertNodeInListAfter(sourceFile, ts.last(bindingPattern.elements), element); + } + else { + changes.replaceNode(sourceFile, bindingPattern, ts.createObjectBindingPattern([element])); + } + } } function addNamespaceQualifier(changes, sourceFile, _a) { var namespacePrefix = _a.namespacePrefix, position = _a.position; @@ -129393,21 +129540,47 @@ var ts; var quote = ts.getQuoteFromPreference(quotePreference); return "import(" + quote + moduleSpecifier + quote + ")."; } - function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a, blankLineBetween) { - var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport, typeOnly = _a.typeOnly; + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); - if (defaultImport !== undefined || namedImports.length) { - ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, typeOnly), /*blankLineBetween*/ blankLineBetween); + if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + ts.insertImport(changes, sourceFile, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly), /*blankLineBetween*/ blankLineBetween); } + var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly; if (namespaceLikeImport) { - ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) : - namespaceLikeImport.importKind === 4 /* ConstEquals */ ? createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier) : - ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier), /*blankLineBetween*/ blankLineBetween); + var declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ + ? ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause( + /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, /*blankLineBetween*/ blankLineBetween); + } + } + function addNewRequires(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + var _a, _b; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + // const { default: foo, bar, etc } = require('./mod'); + if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || []; + if (imports.defaultImport) { + bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport)); + } + var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + } + // const foo = require('./mod'); + if (imports.namespaceLikeImport) { + var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, blankLineBetween); } } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.createIdentifier(name), + return ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(typeof name === "string" ? ts.createIdentifier(name) : name, /*type*/ undefined, ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier])) ], 2 /* Const */)); } @@ -135831,7 +136004,7 @@ var ts; get: function () { return ts.symbolName(this); }, - enumerable: true, + enumerable: false, configurable: true }); SymbolObject.prototype.getEscapedName = function () { @@ -135878,7 +136051,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return IdentifierObject; @@ -135893,7 +136066,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return PrivateIdentifierObject; @@ -135986,7 +136159,7 @@ var ts; } return undefined; }, - enumerable: true, + enumerable: false, configurable: true }); return TypeObject; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 2c9e1689450..ea532d504ce 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -3920,6 +3920,9 @@ var ts; CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter"; CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter"; CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType"; + CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType"; + CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped"; + CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant"; CheckFlags[CheckFlags["Partial"] = 48] = "Partial"; @@ -4046,16 +4049,16 @@ var ts; TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ - TypeFlags[TypeFlags["IncludesMask"] = 68943871] = "IncludesMask"; + TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask"; // The following flags are used for different purposes during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable"; /* @internal */ - TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType"; + TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType"; /* @internal */ - TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard"; + TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ - TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject"; + TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -4097,6 +4100,12 @@ var ts; ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; /* @internal */ ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; @@ -7340,6 +7349,7 @@ var ts; Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), + Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -14516,6 +14526,15 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; + function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument); + } + ts.isRequireVariableDeclaration = isRequireVariableDeclaration; + function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) { + if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + } + ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement; function isSingleOrDoubleQuote(charCode) { return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } @@ -15094,19 +15113,22 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - return getHostSignatureFromJSDocHost(getJSDocHost(node)); + var host = getEffectiveJSDocHost(node); + return host && ts.isFunctionLike(host) ? host : undefined; } ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; - function getHostSignatureFromJSDocHost(host) { + function getEffectiveJSDocHost(node) { + var host = getJSDocHost(node); var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || host; - return decl && ts.isFunctionLike(decl) ? decl : undefined; + return decl; } - ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + ts.getEffectiveJSDocHost = getEffectiveJSDocHost; + /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */ function getJSDocHost(node) { return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent; } @@ -34951,6 +34973,9 @@ var ts; getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleName: function (moduleSpecifier) { + return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); + }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, tryGetThisTypeAt: function (node, includeGlobalThis) { node = ts.getParseTreeNode(node); @@ -36736,7 +36761,7 @@ var ts; return resolved; } function getTargetOfExportAssignment(node, dontResolveAlias) { - var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + var expression = ts.isExportAssignment(node) ? node.expression : node.right; var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); return resolved; @@ -37044,8 +37069,8 @@ var ts; return getDeclarationOfJSPrototypeContainer(symbol); } } - var sig = ts.getHostSignatureFromJSDocHost(host); - if (sig) { + var sig = ts.getEffectiveJSDocHost(node); + if (sig && ts.isFunctionLike(sig)) { var symbol = getSymbolOfNode(sig); return symbol && symbol.valueDeclaration; } @@ -38107,6 +38132,7 @@ var ts; context.encounteredError = true; return undefined; // TODO: GH#18217 } + type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -39960,7 +39986,7 @@ var ts; var varName = getUnusedName(name, symbol); // We have to use `getWidenedType` here since the object within a json file is unwidened within the file // (Unwidened types can only exist in expression contexts and should never be serialized) - var typeToSerialize = getWidenedType(getTypeOfSymbol(symbol)); + var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol))); if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) { // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */); @@ -40815,6 +40841,7 @@ var ts; var type; if (pattern.kind === 189 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { + parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; @@ -41626,13 +41653,17 @@ var ts; return links.type; } function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 65536 /* DeferredType */) { + var checkFlags = ts.getCheckFlags(symbol); + if (checkFlags & 65536 /* DeferredType */) { return getTypeOfSymbolWithDeferredType(symbol); } - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + if (checkFlags & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 8192 /* ReverseMapped */) { + if (checkFlags & 262144 /* Mapped */) { + return getTypeOfMappedSymbol(symbol); + } + if (checkFlags & 8192 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -41920,7 +41951,7 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReturnTypeOfSignature(constructors[0]); + baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; @@ -41963,8 +41994,8 @@ var ts; } // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed? // There's no reason a `T` should be allowed while a `Readonly` should not. - return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType)); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -41973,7 +42004,7 @@ var ts; if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); + var baseType = getReducedType(getTypeFromTypeNode(node)); if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -43138,7 +43169,6 @@ var ts; // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); - var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (isTypeUsableAsPropertyName(t)) { @@ -43148,13 +43178,10 @@ var ts; !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); - var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); - // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the - // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks - // mode, if the underlying property is optional we remove 'undefined' from the type. - prop.type = strictNullChecks && isOptional && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : - propType; + var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */; + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0)); + prop.mappedType = type; + prop.mapper = templateMapper; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; prop.declarations = modifiersProp.declarations; @@ -43162,14 +43189,38 @@ var ts; prop.nameType = t; members.set(propName, prop); } - else if (t.flags & (1 /* Any */ | 4 /* String */)) { - stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); - } - else if (t.flags & (8 /* Number */ | 32 /* Enum */)) { - numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) { + var propType = instantiateType(templateType, templateMapper); + if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else { + numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } } } } + function getTypeOfMappedSymbol(symbol) { + if (!symbol.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType); + var propType = instantiateType(templateType, symbol.mapper); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : + symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (!popTypeResolution()) { + error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType)); + type = errorType; + } + symbol.type = type; + } + return symbol.type; + } function getTypeParameterFromMappedType(type) { return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); @@ -43304,7 +43355,7 @@ var ts; return type.resolvedProperties; } function getPropertiesOfType(type) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); @@ -43623,7 +43674,7 @@ var ts; /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the - * type itself. Note that the apparent type of a union type is the union type itself. + * type itself. */ function getApparentType(type) { var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; @@ -43651,7 +43702,7 @@ var ts; for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var current = _a[_i]; var type = getApparentType(current); - if (type !== errorType) { + if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { @@ -43723,6 +43774,9 @@ var ts; if (isLiteralType(type)) { checkFlags |= 128 /* HasLiteralType */; } + if (type.flags & 131072 /* Never */) { + checkFlags |= 131072 /* HasNeverType */; + } propTypes.push(type); } ts.addRange(propTypes, indexTypes); @@ -43769,6 +43823,41 @@ var ts; // We need to filter out partial properties in union types return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined; } + /** + * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types. + * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'. + * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when + * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. + */ + function getReducedType(type) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); + } + else if (type.flags & 2097152 /* Intersection */) { + if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + } + return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + } + return type; + } + function getReducedUnionType(unionType) { + var reducedTypes = ts.sameMap(unionType.types, getReducedType); + if (reducedTypes === unionType.types) { + return unionType; + } + var reduced = getUnionType(reducedTypes); + if (reduced.flags & 1048576 /* Union */) { + reduced.resolvedReducedType = reduced; + } + return reduced; + } + function isDiscriminantWithNeverType(prop) { + return !(prop.flags & 16777216 /* Optional */) && + (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && + !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -43778,7 +43867,7 @@ var ts; * @param name a name of property to look up in a given type */ function getPropertyOfType(type, name) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); @@ -43814,7 +43903,7 @@ var ts; * maps primitive types and type parameters are to their apparent types. */ function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); + return getSignaturesOfStructuredType(getApparentType(getReducedType(type)), kind); } function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 3670016 /* StructuredType */) { @@ -43829,12 +43918,12 @@ var ts; // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); + return getIndexInfoOfStructuredType(getApparentType(getReducedType(type)), kind); } // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); + return getIndexTypeOfStructuredType(getApparentType(getReducedType(type)), kind); } function getImplicitIndexTypeOfType(type, kind) { if (isObjectTypeWithInferableIndex(type)) { @@ -45116,14 +45205,14 @@ var ts; } // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; if (flags & 66846720 /* StructuredOrInstantiable */) includes |= 262144 /* IncludesStructuredOrInstantiable */; if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) - includes |= 2097152 /* IncludesNonWideningType */; + includes |= 4194304 /* IncludesNonWideningType */; } else { var len = typeSet.length; @@ -45229,7 +45318,7 @@ var ts; var includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */) { if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; + return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1 /* Literal */: @@ -45244,12 +45333,14 @@ var ts; break; } if (typeSet.length === 0) { - return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType : - includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : + return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -45321,15 +45412,15 @@ var ts; return addTypesToIntersection(typeSet, includes, type.types); } if (isEmptyAnonymousObjectType(type)) { - if (!(includes & 8388608 /* IncludesEmptyObject */)) { - includes |= 8388608 /* IncludesEmptyObject */; + if (!(includes & 16777216 /* IncludesEmptyObject */)) { + includes |= 16777216 /* IncludesEmptyObject */; typeSet.set(type.id.toString(), type); } } else { if (flags & 3 /* AnyOrUnknown */) { if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; } else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) { if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) { @@ -45339,7 +45430,7 @@ var ts; } typeSet.set(type.id.toString(), type); } - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; } return includes; } @@ -45472,7 +45563,7 @@ var ts; // a void-like type and a type known to be non-void-like, or // a non-primitive type and a type known to be primitive. if (includes & 131072 /* Never */ || - strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 8388608 /* IncludesEmptyObject */) || + strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) || includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || @@ -45482,7 +45573,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType; + return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType; } if (!strictNullChecks && includes & 98304 /* Nullable */) { return includes & 32768 /* Undefined */ ? undefinedType : nullType; @@ -45493,7 +45584,7 @@ var ts; includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { + if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { @@ -45598,6 +45689,7 @@ var ts; } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + type = getReducedType(type); return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : @@ -45987,7 +46079,7 @@ var ts; // In the following we resolve T[K] to the type of the property in T selected by K. // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. - var apparentObjectType = getApparentType(objectType); + var apparentObjectType = getApparentType(getReducedType(objectType)); if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; var wasMissingProp = false; @@ -46883,7 +46975,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { + return mapType(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { var replacementMapper = createReplacementMapper(typeVariable, t, mapper); return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) : @@ -47945,7 +48037,8 @@ var ts; } } else { - if (!(source.flags === target.flags && source.flags & 66584576 /* Substructure */)) + if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) && + source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */)) return false; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { @@ -47963,16 +48056,17 @@ var ts; return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { - do { + while (true) { var t = isFreshLiteralType(type) ? type.regularType : ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : - type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : - type; + type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) : + type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : + type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : + type; if (t === type) break; type = t; - } while (true); + } return type; } /** @@ -51121,6 +51215,7 @@ var ts; } } else { + source = getReducedType(source); if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. @@ -51743,9 +51838,6 @@ var ts; } return false; } - function isSyntheticThisPropertyAccess(expr) { - return ts.isAccessExpression(expr) && expr.expression.kind === 104 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */); - } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -52996,11 +53088,6 @@ var ts; if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { - return declaredType; - } return type; } if (type.flags & 1 /* Any */ && literal.text === "function") { @@ -53174,16 +53261,6 @@ var ts; if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' - // references might reference a different 'y' property. However, we make an exception - // for property accesses where x is a synthetic 'this' expression, indicating that we - // were called from isPropertyInitializedInConstructor. Without this exception, - // initializations of 'this' properties that occur before a 'this instanceof XXX' - // check would not be considered. - if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) { - return declaredType; - } return type; } // Check that right operand is a function type with a prototype property @@ -53256,9 +53333,6 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } } } return type; @@ -55217,7 +55291,7 @@ var ts; hasComputedStringProperty = false; hasComputedNumberProperty = false; } - var type = checkExpression(memberDecl.expression); + var type = getReducedType(checkExpression(memberDecl.expression)); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; @@ -55404,7 +55478,7 @@ var ts; spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -62228,15 +62302,14 @@ var ts; checkSignatureDeclaration(node); } function checkJSDocImplementsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); - return; } } function checkJSDocAugmentsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } @@ -64263,7 +64336,7 @@ var ts; } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); + var t = getReducedType(getTypeFromTypeNode(typeRefNode)); if (t !== errorType) { if (isValidBaseType(t)) { var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? @@ -73472,9 +73545,7 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) - ? target.expression - : target; + return target; } } ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; @@ -76643,7 +76714,7 @@ var ts; /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), /*type*/ undefined, iife) - ], languageVersion > 1 /* ES5 */ ? 2 /* Const */ : undefined)); + ], languageVersion > 1 /* ES5 */ ? 1 /* Let */ : undefined)); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); @@ -78382,9 +78453,11 @@ var ts; if (node.isTypeOnly) { return undefined; } - if (!node.exportClause) { - // Elide a star export if the module it references does not export a value. - return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) { + // never elide `export from ` declarations - + // they should be kept for sideffects/untyped exports, even when the + // type checker doesn't know about any exports + return node; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. @@ -107981,6 +108054,10 @@ var ts; : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); } ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsModules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); }); + } + ts.programContainsModules = programContainsModules; function programContainsEs6Modules(program) { return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); } @@ -108118,7 +108195,8 @@ var ts; } ts.findModifier = findModifier; function insertImport(changes, sourceFile, importDecl, blankLineBetween) { - var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var importKindPredicate = importDecl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; + var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); }); if (lastImportDeclaration) { changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); } @@ -111689,20 +111767,17 @@ var ts; filterGlobalCompletion(symbols); } function shouldOfferImportCompletions() { - // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs) + // If not already a module, must have modules enabled. if (!preferences.includeCompletionsForModuleExports) return false; // If already using ES6 modules, OK to continue using them. - if (sourceFile.externalModuleIndicator) + if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; - // If already using commonjs, don't introduce ES6. - if (sourceFile.commonJsModuleIndicator) - return false; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) return true; // If some file is using ES6 modules, assume that it's OK to add more. - return ts.programContainsEs6Modules(program); + return ts.programContainsModules(program); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { @@ -111845,6 +111920,7 @@ var ts; var startTime = ts.timestamp(); log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : "")); var seenResolvedModules = ts.createMap(); + var seenExports = ts.createMap(); /** Bucket B */ var aliasesToAlreadyIncludedSymbols = ts.createMap(); /** Bucket C */ @@ -111865,17 +111941,20 @@ var ts; } // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { + if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, isNonGlobalDeclaration)) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } - for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; + var symbolId = ts.getSymbolId(symbol).toString(); + // `getExportsAndPropertiesOfModule` can include duplicates + if (!ts.addToSeen(seenExports, symbolId)) { + continue; + } // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) { continue; } - var symbolId = ts.getSymbolId(symbol).toString(); // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol; // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). @@ -112859,6 +112938,15 @@ var ts; } } } + function isNonGlobalDeclaration(declaration) { + var sourceFile = declaration.getSourceFile(); + // If the file is not a module, the declaration is global + if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { + return false; + } + // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation + return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -128904,7 +128992,8 @@ var ts; var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker)); var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, sourceFile, compilerOptions, checker, program.getSourceFiles()); var preferTypeOnlyImport = !!usageIsTypeOnly && compilerOptions.importsNotUsedAsValues === 2 /* Error */; - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, host, preferences); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, useRequire, host, preferences); addImport({ fixes: [fix], symbolName: symbolName }); } function addImport(info) { @@ -128918,11 +129007,11 @@ var ts; importType.push(fix); break; case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - var key = String(ts.getNodeId(importClause)); + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; + var key = String(ts.getNodeId(importClauseOrBindingPattern)); var entry = addToExisting.get(key); if (!entry) { - addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); + addToExisting.set(key, entry = { importClauseOrBindingPattern: importClauseOrBindingPattern, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); } if (importKind === 0 /* Named */) { ts.pushIfUnique(entry.namedImports, symbolName); @@ -128934,10 +129023,10 @@ var ts; break; } case 3 /* AddNew */: { - var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, typeOnly = fix.typeOnly; + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, useRequire = fix.useRequire, typeOnly = fix.typeOnly; var entry = newImports.get(moduleSpecifier); if (!entry) { - newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly }); + newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire }); lastModuleSpecifier = moduleSpecifier; } else { @@ -128950,9 +129039,9 @@ var ts; entry.defaultImport = symbolName; break; case 0 /* Named */: - ts.pushIfUnique(entry.namedImports, symbolName); + ts.pushIfUnique(entry.namedImports || (entry.namedImports = []), symbolName); break; - case 3 /* Equals */: + case 3 /* CommonJS */: case 2 /* Namespace */: ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName, "Namespacelike import shoudl be missing or match symbolName"); entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; @@ -128975,11 +129064,13 @@ var ts; addImportType(changeTracker, sourceFile, fix, quotePreference); } addToExisting.forEach(function (_a) { - var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; - doAddExistingFix(changeTracker, sourceFile, importClause, defaultImport, namedImports, canUseTypeOnlyImport); + var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; + doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport); }); - newImports.forEach(function (imports, moduleSpecifier) { - addNewImports(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); + newImports.forEach(function (_a, moduleSpecifier) { + var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]); + var addDeclarations = useRequire ? addNewRequires : addNewImports; + addDeclarations(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); }); } } @@ -128997,22 +129088,22 @@ var ts; ImportKind[ImportKind["Named"] = 0] = "Named"; ImportKind[ImportKind["Default"] = 1] = "Default"; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["Equals"] = 3] = "Equals"; - ImportKind[ImportKind["ConstEquals"] = 4] = "ConstEquals"; + ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, sourceFile, compilerOptions, program.getTypeChecker(), program.getSourceFiles()); - var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, exportInfos, host, preferences)).moduleSpecifier; - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, host, preferences); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, host, preferences) { + function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, program, sourceFile, host, preferences)); + return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -129029,7 +129120,7 @@ var ts; if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); } - for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); @@ -129046,13 +129137,13 @@ var ts; } function getFixForImport(exportInfos, symbolName, /** undefined only for missing JSX namespace */ - position, preferTypeOnlyImport, program, sourceFile, host, preferences) { + position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. - var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, host, preferences); + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences); return __spreadArrays((useNamespace ? [useNamespace] : ts.emptyArray), addImport); } function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { @@ -129070,58 +129161,91 @@ var ts; // and it is up to the user to decide which one fits best. return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + var namespacePrefix = getNamespaceLikeImportText(declaration); + if (namespacePrefix) { + var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position }; } } }); } + function getTargetModuleFromNamespaceLikeImport(declaration, checker) { + var _a; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); + case 253 /* ImportEqualsDeclaration */: + return checker.getAliasedSymbol(declaration.symbol); + case 254 /* ImportDeclaration */: + var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); + return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); + default: + return ts.Debug.assertNever(declaration); + } + } + function getNamespaceLikeImportText(declaration) { + var _a, _b, _c; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; + case 253 /* ImportEqualsDeclaration */: + return declaration.name.text; + case 254 /* ImportDeclaration */: + return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; + default: + return ts.Debug.assertNever(declaration); + } + } function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind !== 254 /* ImportDeclaration */) + if (declaration.kind === 253 /* ImportEqualsDeclaration */) return undefined; + if (declaration.kind === 242 /* VariableDeclaration */) { + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 189 /* ObjectBindingPattern */ + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false } + : undefined; + } var importClause = declaration.importClause; if (!importClause) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 257 /* NamedImports */) - ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind, canUseTypeOnlyImport: canUseTypeOnlyImport } + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; }); } - function getNamespaceImportName(declaration) { - if (declaration.kind === 254 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 256 /* NamespaceImport */ ? namedBindings.name : undefined; - } - else { - return declaration.name; - } - } function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) - && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, exportedSymbolIsTypeOnly: exportedSymbolIsTypeOnly } : undefined; + if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined; + } + if (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) { + return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + } }); } - function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, moduleSymbols, host, preferences) { + function shouldUseRequire(sourceFile, compilerOptions) { + return ts.isSourceFileJS(sourceFile) + && !sourceFile.externalModuleIndicator + && (!!sourceFile.commonJsModuleIndicator || ts.getEmitModuleKind(compilerOptions) < ts.ModuleKind.ES2015); + } + function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); + var compilerOptions = program.getCompilerOptions(); var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, compilerOptions, sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.checkDefined(position, "position should be defined") } - : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, typeOnly: preferTypeOnlyImport }; + : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; }); }); // Sort by presence in package.json, then shortest paths first @@ -129137,19 +129261,18 @@ var ts; return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } - function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, host, preferences) { - var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport); }); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, exportInfos, host, preferences); + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } - function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport) { + function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 254 /* ImportDeclaration */ - ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 265 /* ExternalModuleReference */ - ? declaration.moduleReference.expression - : undefined; - return expression && ts.isStringLiteral(expression) - ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind, typeOnly: preferTypeOnlyImport } + var moduleSpecifier = declaration.kind === 254 /* ImportDeclaration */ ? declaration.moduleSpecifier : + declaration.kind === 242 /* VariableDeclaration */ ? declaration.initializer.arguments[0] : + declaration.moduleReference.kind === 265 /* ExternalModuleReference */ ? declaration.moduleReference.expression : + undefined; + return moduleSpecifier && ts.isStringLiteral(moduleSpecifier) + ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } : undefined; } function getFixesInfo(context, errorCode, pos) { @@ -129168,7 +129291,8 @@ var ts; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; - var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, program, sourceFile, host, preferences); + var useRequire = shouldUseRequire(sourceFile, program.getCompilerOptions()); + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -129194,9 +129318,9 @@ var ts; case ts.ModuleKind.CommonJS: case ts.ModuleKind.UMD: if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 3 /* CommonJS */; } - return 3 /* Equals */; + return 3 /* CommonJS */; case ts.ModuleKind.System: case ts.ModuleKind.ES2015: case ts.ModuleKind.ES2020: @@ -129219,11 +129343,13 @@ var ts; : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); - var preferTypeOnlyImport = program.getCompilerOptions().importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); + var compilerOptions = program.getCompilerOptions(); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program, host); var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, program, sourceFile, host, preferences); + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } @@ -129274,7 +129400,7 @@ var ts; // 2. 'import =' will not work in JavaScript, so the decision is between a default // and const/require. if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 1 /* Default */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 1 /* Default */ : 3 /* CommonJS */; } // 3. At this point the most correct choice is probably 'import =', but people // really hate that, so look to see if the importing file has any precedent @@ -129282,12 +129408,12 @@ var ts; for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (ts.isImportEqualsDeclaration(statement)) { - return 3 /* Equals */; + return 3 /* CommonJS */; } } // 4. We have no precedent to go on, so just use a default import if // allowSyntheticDefaultImports/esModuleInterop is enabled. - return allowSyntheticDefaults ? 1 /* Default */ : 3 /* Equals */; + return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); @@ -129335,16 +129461,18 @@ var ts; addImportType(changes, sourceFile, fix, quotePreference); return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport, moduleSpecifier = fix.moduleSpecifier; + doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! } case 3 /* AddNew */: { - var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly; - addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined, typeOnly: typeOnly } - : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined, typeOnly: typeOnly } - : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }, /*blankLineBetween*/ true); + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire; + var addDeclarations = useRequire ? addNewRequires : addNewImports; + var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } : + importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } : + { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }; + addDeclarations(changes, sourceFile, moduleSpecifier, quotePreference, importsCollection, /*blankLineBetween*/ true); return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: @@ -129352,6 +129480,16 @@ var ts; } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) { + if (clause.kind === 189 /* ObjectBindingPattern */) { + if (defaultImport) { + addElementToBindingPattern(clause, defaultImport, "default"); + } + for (var _i = 0, namedImports_1 = namedImports; _i < namedImports_1.length; _i++) { + var specifier = namedImports_1[_i]; + addElementToBindingPattern(clause, specifier, /*propertyName*/ undefined); + } + return; + } var convertTypeOnlyToRegular = !canUseTypeOnlyImport && clause.isTypeOnly; if (defaultImport) { ts.Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one"); @@ -129360,19 +129498,19 @@ var ts; if (namedImports.length) { var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { - for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { - var spec = specifiers_1[_i]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var spec = specifiers_1[_a]; changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); } } else { if (specifiers.length) { - var namedImports_1 = ts.createNamedImports(specifiers); + var namedImports_2 = ts.createNamedImports(specifiers); if (clause.namedBindings) { - changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_2); } else { - changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_1); + changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_2); } } } @@ -129380,6 +129518,15 @@ var ts; if (convertTypeOnlyToRegular) { changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(clause, sourceFile)); } + function addElementToBindingPattern(bindingPattern, name, propertyName) { + var element = ts.createBindingElement(/*dotDotDotToken*/ undefined, propertyName, name); + if (bindingPattern.elements.length) { + changes.insertNodeInListAfter(sourceFile, ts.last(bindingPattern.elements), element); + } + else { + changes.replaceNode(sourceFile, bindingPattern, ts.createObjectBindingPattern([element])); + } + } } function addNamespaceQualifier(changes, sourceFile, _a) { var namespacePrefix = _a.namespacePrefix, position = _a.position; @@ -129393,21 +129540,47 @@ var ts; var quote = ts.getQuoteFromPreference(quotePreference); return "import(" + quote + moduleSpecifier + quote + ")."; } - function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a, blankLineBetween) { - var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport, typeOnly = _a.typeOnly; + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); - if (defaultImport !== undefined || namedImports.length) { - ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, typeOnly), /*blankLineBetween*/ blankLineBetween); + if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + ts.insertImport(changes, sourceFile, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly), /*blankLineBetween*/ blankLineBetween); } + var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly; if (namespaceLikeImport) { - ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) : - namespaceLikeImport.importKind === 4 /* ConstEquals */ ? createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier) : - ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier), /*blankLineBetween*/ blankLineBetween); + var declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ + ? ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause( + /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, /*blankLineBetween*/ blankLineBetween); + } + } + function addNewRequires(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + var _a, _b; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + // const { default: foo, bar, etc } = require('./mod'); + if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || []; + if (imports.defaultImport) { + bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport)); + } + var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + } + // const foo = require('./mod'); + if (imports.namespaceLikeImport) { + var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier); + ts.insertImport(changes, sourceFile, declaration, blankLineBetween); } } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.createIdentifier(name), + return ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(typeof name === "string" ? ts.createIdentifier(name) : name, /*type*/ undefined, ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier])) ], 2 /* Const */)); } @@ -135831,7 +136004,7 @@ var ts; get: function () { return ts.symbolName(this); }, - enumerable: true, + enumerable: false, configurable: true }); SymbolObject.prototype.getEscapedName = function () { @@ -135878,7 +136051,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return IdentifierObject; @@ -135893,7 +136066,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return PrivateIdentifierObject; @@ -135986,7 +136159,7 @@ var ts; } return undefined; }, - enumerable: true, + enumerable: false, configurable: true }); return TypeObject; diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 403e6132e2e..27253a5adb0 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -3759,6 +3759,9 @@ var ts; CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter"; CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter"; CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType"; + CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType"; + CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped"; + CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant"; CheckFlags[CheckFlags["Partial"] = 48] = "Partial"; @@ -3885,16 +3888,16 @@ var ts; TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ - TypeFlags[TypeFlags["IncludesMask"] = 68943871] = "IncludesMask"; + TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask"; // The following flags are used for different purposes during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable"; /* @internal */ - TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType"; + TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType"; /* @internal */ - TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard"; + TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ - TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject"; + TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -3936,6 +3939,12 @@ var ts; ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; /* @internal */ ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; @@ -7179,6 +7188,7 @@ var ts; Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), + Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -14355,6 +14365,15 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; + function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument); + } + ts.isRequireVariableDeclaration = isRequireVariableDeclaration; + function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) { + if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + } + ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement; function isSingleOrDoubleQuote(charCode) { return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } @@ -14933,19 +14952,22 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - return getHostSignatureFromJSDocHost(getJSDocHost(node)); + var host = getEffectiveJSDocHost(node); + return host && ts.isFunctionLike(host) ? host : undefined; } ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; - function getHostSignatureFromJSDocHost(host) { + function getEffectiveJSDocHost(node) { + var host = getJSDocHost(node); var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || host; - return decl && ts.isFunctionLike(decl) ? decl : undefined; + return decl; } - ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + ts.getEffectiveJSDocHost = getEffectiveJSDocHost; + /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */ function getJSDocHost(node) { return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent; } @@ -34790,6 +34812,9 @@ var ts; getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleName: function (moduleSpecifier) { + return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); + }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, tryGetThisTypeAt: function (node, includeGlobalThis) { node = ts.getParseTreeNode(node); @@ -36575,7 +36600,7 @@ var ts; return resolved; } function getTargetOfExportAssignment(node, dontResolveAlias) { - var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + var expression = ts.isExportAssignment(node) ? node.expression : node.right; var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); return resolved; @@ -36883,8 +36908,8 @@ var ts; return getDeclarationOfJSPrototypeContainer(symbol); } } - var sig = ts.getHostSignatureFromJSDocHost(host); - if (sig) { + var sig = ts.getEffectiveJSDocHost(node); + if (sig && ts.isFunctionLike(sig)) { var symbol = getSymbolOfNode(sig); return symbol && symbol.valueDeclaration; } @@ -37946,6 +37971,7 @@ var ts; context.encounteredError = true; return undefined; // TODO: GH#18217 } + type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -39799,7 +39825,7 @@ var ts; var varName = getUnusedName(name, symbol); // We have to use `getWidenedType` here since the object within a json file is unwidened within the file // (Unwidened types can only exist in expression contexts and should never be serialized) - var typeToSerialize = getWidenedType(getTypeOfSymbol(symbol)); + var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol))); if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) { // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */); @@ -40654,6 +40680,7 @@ var ts; var type; if (pattern.kind === 189 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { + parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; @@ -41465,13 +41492,17 @@ var ts; return links.type; } function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 65536 /* DeferredType */) { + var checkFlags = ts.getCheckFlags(symbol); + if (checkFlags & 65536 /* DeferredType */) { return getTypeOfSymbolWithDeferredType(symbol); } - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + if (checkFlags & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 8192 /* ReverseMapped */) { + if (checkFlags & 262144 /* Mapped */) { + return getTypeOfMappedSymbol(symbol); + } + if (checkFlags & 8192 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -41759,7 +41790,7 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReturnTypeOfSignature(constructors[0]); + baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; @@ -41802,8 +41833,8 @@ var ts; } // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed? // There's no reason a `T` should be allowed while a `Readonly` should not. - return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType)); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -41812,7 +41843,7 @@ var ts; if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); + var baseType = getReducedType(getTypeFromTypeNode(node)); if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -42977,7 +43008,6 @@ var ts; // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); - var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (isTypeUsableAsPropertyName(t)) { @@ -42987,13 +43017,10 @@ var ts; !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); - var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); - // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the - // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks - // mode, if the underlying property is optional we remove 'undefined' from the type. - prop.type = strictNullChecks && isOptional && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : - propType; + var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */; + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0)); + prop.mappedType = type; + prop.mapper = templateMapper; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; prop.declarations = modifiersProp.declarations; @@ -43001,14 +43028,38 @@ var ts; prop.nameType = t; members.set(propName, prop); } - else if (t.flags & (1 /* Any */ | 4 /* String */)) { - stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); - } - else if (t.flags & (8 /* Number */ | 32 /* Enum */)) { - numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) { + var propType = instantiateType(templateType, templateMapper); + if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else { + numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } } } } + function getTypeOfMappedSymbol(symbol) { + if (!symbol.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType); + var propType = instantiateType(templateType, symbol.mapper); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : + symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (!popTypeResolution()) { + error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType)); + type = errorType; + } + symbol.type = type; + } + return symbol.type; + } function getTypeParameterFromMappedType(type) { return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); @@ -43143,7 +43194,7 @@ var ts; return type.resolvedProperties; } function getPropertiesOfType(type) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); @@ -43462,7 +43513,7 @@ var ts; /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the - * type itself. Note that the apparent type of a union type is the union type itself. + * type itself. */ function getApparentType(type) { var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; @@ -43490,7 +43541,7 @@ var ts; for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var current = _a[_i]; var type = getApparentType(current); - if (type !== errorType) { + if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { @@ -43562,6 +43613,9 @@ var ts; if (isLiteralType(type)) { checkFlags |= 128 /* HasLiteralType */; } + if (type.flags & 131072 /* Never */) { + checkFlags |= 131072 /* HasNeverType */; + } propTypes.push(type); } ts.addRange(propTypes, indexTypes); @@ -43608,6 +43662,41 @@ var ts; // We need to filter out partial properties in union types return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined; } + /** + * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types. + * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'. + * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when + * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. + */ + function getReducedType(type) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); + } + else if (type.flags & 2097152 /* Intersection */) { + if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + } + return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + } + return type; + } + function getReducedUnionType(unionType) { + var reducedTypes = ts.sameMap(unionType.types, getReducedType); + if (reducedTypes === unionType.types) { + return unionType; + } + var reduced = getUnionType(reducedTypes); + if (reduced.flags & 1048576 /* Union */) { + reduced.resolvedReducedType = reduced; + } + return reduced; + } + function isDiscriminantWithNeverType(prop) { + return !(prop.flags & 16777216 /* Optional */) && + (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && + !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -43617,7 +43706,7 @@ var ts; * @param name a name of property to look up in a given type */ function getPropertyOfType(type, name) { - type = getApparentType(type); + type = getApparentType(getReducedType(type)); if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); @@ -43653,7 +43742,7 @@ var ts; * maps primitive types and type parameters are to their apparent types. */ function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); + return getSignaturesOfStructuredType(getApparentType(getReducedType(type)), kind); } function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 3670016 /* StructuredType */) { @@ -43668,12 +43757,12 @@ var ts; // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); + return getIndexInfoOfStructuredType(getApparentType(getReducedType(type)), kind); } // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); + return getIndexTypeOfStructuredType(getApparentType(getReducedType(type)), kind); } function getImplicitIndexTypeOfType(type, kind) { if (isObjectTypeWithInferableIndex(type)) { @@ -44955,14 +45044,14 @@ var ts; } // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; if (flags & 66846720 /* StructuredOrInstantiable */) includes |= 262144 /* IncludesStructuredOrInstantiable */; if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) - includes |= 2097152 /* IncludesNonWideningType */; + includes |= 4194304 /* IncludesNonWideningType */; } else { var len = typeSet.length; @@ -45068,7 +45157,7 @@ var ts; var includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */) { if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; + return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1 /* Literal */: @@ -45083,12 +45172,14 @@ var ts; break; } if (typeSet.length === 0) { - return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType : - includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : + return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -45160,15 +45251,15 @@ var ts; return addTypesToIntersection(typeSet, includes, type.types); } if (isEmptyAnonymousObjectType(type)) { - if (!(includes & 8388608 /* IncludesEmptyObject */)) { - includes |= 8388608 /* IncludesEmptyObject */; + if (!(includes & 16777216 /* IncludesEmptyObject */)) { + includes |= 16777216 /* IncludesEmptyObject */; typeSet.set(type.id.toString(), type); } } else { if (flags & 3 /* AnyOrUnknown */) { if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; } else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) { if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) { @@ -45178,7 +45269,7 @@ var ts; } typeSet.set(type.id.toString(), type); } - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; } return includes; } @@ -45311,7 +45402,7 @@ var ts; // a void-like type and a type known to be non-void-like, or // a non-primitive type and a type known to be primitive. if (includes & 131072 /* Never */ || - strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 8388608 /* IncludesEmptyObject */) || + strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) || includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || @@ -45321,7 +45412,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType; + return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType; } if (!strictNullChecks && includes & 98304 /* Nullable */) { return includes & 32768 /* Undefined */ ? undefinedType : nullType; @@ -45332,7 +45423,7 @@ var ts; includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { + if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { @@ -45437,6 +45528,7 @@ var ts; } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + type = getReducedType(type); return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : @@ -45826,7 +45918,7 @@ var ts; // In the following we resolve T[K] to the type of the property in T selected by K. // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. - var apparentObjectType = getApparentType(objectType); + var apparentObjectType = getApparentType(getReducedType(objectType)); if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; var wasMissingProp = false; @@ -46722,7 +46814,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { + return mapType(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { var replacementMapper = createReplacementMapper(typeVariable, t, mapper); return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) : @@ -47784,7 +47876,8 @@ var ts; } } else { - if (!(source.flags === target.flags && source.flags & 66584576 /* Substructure */)) + if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) && + source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */)) return false; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { @@ -47802,16 +47895,17 @@ var ts; return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { - do { + while (true) { var t = isFreshLiteralType(type) ? type.regularType : ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : - type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : - type; + type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) : + type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : + type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : + type; if (t === type) break; type = t; - } while (true); + } return type; } /** @@ -50960,6 +51054,7 @@ var ts; } } else { + source = getReducedType(source); if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. @@ -51582,9 +51677,6 @@ var ts; } return false; } - function isSyntheticThisPropertyAccess(expr) { - return ts.isAccessExpression(expr) && expr.expression.kind === 104 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */); - } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -52835,11 +52927,6 @@ var ts; if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { - return declaredType; - } return type; } if (type.flags & 1 /* Any */ && literal.text === "function") { @@ -53013,16 +53100,6 @@ var ts; if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' - // references might reference a different 'y' property. However, we make an exception - // for property accesses where x is a synthetic 'this' expression, indicating that we - // were called from isPropertyInitializedInConstructor. Without this exception, - // initializations of 'this' properties that occur before a 'this instanceof XXX' - // check would not be considered. - if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) { - return declaredType; - } return type; } // Check that right operand is a function type with a prototype property @@ -53095,9 +53172,6 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } } } return type; @@ -55056,7 +55130,7 @@ var ts; hasComputedStringProperty = false; hasComputedNumberProperty = false; } - var type = checkExpression(memberDecl.expression); + var type = getReducedType(checkExpression(memberDecl.expression)); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; @@ -55243,7 +55317,7 @@ var ts; spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -62067,15 +62141,14 @@ var ts; checkSignatureDeclaration(node); } function checkJSDocImplementsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); - return; } } function checkJSDocAugmentsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } @@ -64102,7 +64175,7 @@ var ts; } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); + var t = getReducedType(getTypeFromTypeNode(typeRefNode)); if (t !== errorType) { if (isValidBaseType(t)) { var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? @@ -73311,9 +73384,7 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) - ? target.expression - : target; + return target; } } ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; @@ -76482,7 +76553,7 @@ var ts; /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), /*type*/ undefined, iife) - ], languageVersion > 1 /* ES5 */ ? 2 /* Const */ : undefined)); + ], languageVersion > 1 /* ES5 */ ? 1 /* Let */ : undefined)); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); @@ -78221,9 +78292,11 @@ var ts; if (node.isTypeOnly) { return undefined; } - if (!node.exportClause) { - // Elide a star export if the module it references does not export a value. - return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) { + // never elide `export from ` declarations - + // they should be kept for sideffects/untyped exports, even when the + // type checker doesn't know about any exports + return node; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index 479efa29956..9cdfcd08e2a 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -758,10 +758,12 @@ "Only_amd_and_system_modules_are_supported_alongside_0_6082": "--{0} 旁仅支持 \"amd\" 和 \"system\" 模块。", "Only_emit_d_ts_declaration_files_6014": "仅发出 \".d.ts\" 声明文件。 ", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "类 \"extends\" 子句当前仅支持具有可选类型参数的标识符/限定名称。", + "Only_named_exports_may_use_export_type_1383": "Only named exports may use 'export type'.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "通过 \"super\" 关键字只能访问基类的公共方法和受保护方法。", "Operator_0_cannot_be_applied_to_type_1_2736": "运算符 \"{0}\" 不能应用于类型 \"{1}\"。", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "运算符“{0}”不能应用于类型“{1}”和“{2}”。", - "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "仅可在 \"tsconfig.json\" 文件中指定选项“{0}”。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "选项“{0}”只能在 \"tsconfig.json\" 文件中指定,或者在命令行上设置为 \"false\" 或 \"null\"。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "选项“{0}”只能在 \"tsconfig.json\" 文件中指定或在命令行上设置为 \"null\"。", "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "仅当提供了选项 \"--inlineSourceMap\" 或选项 \"--sourceMap\" 时,才能使用选项“{0}”。", "Option_0_cannot_be_specified_when_option_target_is_ES3_5048": "选项 \"target\" 为 \"ES3\" 时,不能指定选项 \"{0}\"。", "Option_0_cannot_be_specified_with_option_1_5053": "选项“{0}”不能与选项“{1}”同时指定。", @@ -1035,6 +1037,7 @@ "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "\"Symbol\" 引用不是指全局符号构造函数对象。", "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228": "在不支持本机递归监视的平台上同步调用回调并更新目录观察程序的状态。", "Syntax_Colon_0_6023": "语法: {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "标记“{0}”至少需要“{1}”个参数,但 JSX 工厂“{2}”最多可提供“{3}”个。", "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "可选链中不允许使用带有标记的模板表达式。", "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "\"{0}\" 修饰符只能在 TypeScript 文件中使用。", "The_0_operator_cannot_be_applied_to_type_symbol_2469": "“{0}”运算符不能应用于类型 \"symbol\"。", @@ -1179,6 +1182,7 @@ "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "\"await\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "计算属性类型的值为 \"{0}\",该值不能赋给 \"{1}\" 类型。", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "\"yield*\" 操作数的迭代元素的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Type of property '{0}' circularly references itself in mapped type '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "异步生成器中 \"yield\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "此导入产生的类型。无法调用或构造命名空间样式的导入,这类导入将在运行时导致失败。请考虑改为使用默认导入或这里需要的导入。", "Type_parameter_0_has_a_circular_constraint_2313": "类型参数“{0}”具有循环约束。", diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 71257d1516f..c0b623da1f3 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2220,7 +2220,7 @@ namespace ts { // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return AssignmentDeclarationKind.ExportsProperty; } - if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (isElementAccessExpression(lhs) && isDynamicName(lhs) && lhs.expression.kind !== SyntaxKind.ThisKeyword)) { + if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (isElementAccessExpression(lhs) && isDynamicName(lhs))) { // F.G...x = expr return AssignmentDeclarationKind.Property; }