diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index ec9453bb00c..0e37b0689e0 100644 --- a/lib/cancellationToken.js +++ b/lib/cancellationToken.js @@ -69,5 +69,3 @@ function createCancellationToken(args) { } } module.exports = createCancellationToken; - -//# sourceMappingURL=cancellationToken.js.map diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index a21c3a3335f..7271e1a2328 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Všechny deklarace {0} musí mít stejné modifikátory.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Všechny deklarace {0} musí mít stejné parametry typu.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Všechny deklarace abstraktní metody musí jít po sobě.", + "All_destructured_elements_are_unused_6198": "Žádný z destrukturovaných elementů se nepoužívá.", "All_imports_in_import_declaration_are_unused_6192": "Žádné importy z deklarace importu se nepoužívají.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Povolte výchozí importy z modulů bez výchozího exportu. Nebude to mít vliv na generování kódu, jenom na kontrolu typů.", "Allow_javascript_files_to_be_compiled_6102": "Povolí kompilaci souborů javascript.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Nejde vyvolat objekt, který může být null.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nejde vyvolat objekt, který může být null nebo nedefinovaný.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nejde vyvolat objekt, který může být nedefinovaný.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Projekt {0} se nedá předřadit, protože nemá nastavenou hodnotu outFile.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Typ nejde znovu exportovat, pokud je zadaný příznak --isolatedModules.", "Cannot_read_file_0_Colon_1_5012": "Nejde číst soubor {0}: {1}", "Cannot_redeclare_block_scoped_variable_0_2451": "Nejde předeklarovat proměnnou bloku {0}.", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Zkompilujte projekt podle cesty k jeho konfiguračnímu souboru nebo do složky se souborem tsconfig.json.", "Compiler_option_0_expects_an_argument_6044": "Parametr kompilátoru {0} očekává argument.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Parametr kompilátoru {0} vyžaduje hodnotu typu {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Složené projekty nemůžou zakázat generování deklarací.", "Computed_property_names_are_not_allowed_in_enums_1164": "Názvy počítaných vlastností se ve výčtech nepovolují.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Ve výčtu, jehož členy mají hodnoty typu string, se nepovolují vypočítané hodnoty.", "Concatenate_and_emit_output_to_single_file_6001": "Zřetězit a generovat výstup do jednoho souboru", @@ -271,9 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory odvozených tříd musí obsahovat volání příkazu super.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Není zadaný obsažený soubor a nedá se určit kořenový adresář – přeskakuje se vyhledávání ve složce node_modules.", "Convert_all_constructor_functions_to_classes_95045": "Převést všechny funkce konstruktoru na třídy", + "Convert_all_require_to_import_95048": "Převést všechna volání require na import", "Convert_all_to_default_imports_95035": "Převést vše na výchozí importy", "Convert_function_0_to_class_95002": "Převést funkci {0} na třídu", "Convert_function_to_an_ES2015_class_95001": "Převést funkci na třídu ES2015", + "Convert_require_to_import_95047": "Převést require na import", "Convert_to_ES6_module_95017": "Převést na modul ES6", "Convert_to_default_import_95013": "Převést na výchozí import", "Corrupted_locale_file_0_6051": "Soubor národního prostředí {0} je poškozený.", @@ -326,8 +331,8 @@ "Duplicate_label_0_1114": "Duplicitní popisek {0}", "Duplicate_number_index_signature_2375": "Duplicitní podpis číselného indexu", "Duplicate_string_index_signature_2374": "Duplicitní signatury řetězcového indexu", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Když se cílí na moduly ECMAScript 2015, nejde dynamický import použít.", "Dynamic_import_cannot_have_type_arguments_1326": "Dynamický import nemůže mít argumenty typu.", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Dynamický import se podporuje jenom tehdy, když je příznak --module nastavený na commonjs nebo esNext.", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dynamický import musí mít jako argument jeden specifikátor.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specifikátor dynamického importu musí být typu string, ale tady má typ {0}.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element má implicitně typ any, protože indexový výraz není typu number.", @@ -336,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Vygeneruje jediný soubor se zdrojovými mapováními namísto samostatného souboru.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Vygeneruje zdroj spolu se zdrojovými mapováními v jednom souboru. Vyžaduje, aby byla nastavená možnost --inlineSourceMap nebo --sourceMap.", "Enable_all_strict_type_checking_options_6180": "Povolí všechny možnosti striktní kontroly typů.", + "Enable_project_compilation_6302": "Povolit kompilování projektu", "Enable_strict_checking_of_function_types_6186": "Povolí striktní kontrolu typů funkcí.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Povolí striktní kontrolu inicializace vlastností ve třídách.", "Enable_strict_null_checks_6113": "Povolte striktní kontroly hodnot null.", @@ -397,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Soubor {0} má nepodporovanou příponu, a proto se přeskočí.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Soubor {0} má nepodporovanou příponu. Jediné podporované přípony jsou {1}.", "File_0_is_not_a_module_2306": "Soubor {0} není modul.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Soubor {0} se nenachází v seznamu souborů projektu. Projekty musí uvádět všechny soubory nebo používat vzor include.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Soubor {0} není pod kořenovým adresářem rootDir {1}. Očekává se, že rootDir bude obsahovat všechny zdrojové soubory.", "File_0_not_found_6053": "Soubor {0} se nenašel.", "File_change_detected_Starting_incremental_compilation_6032": "Zjistila se změna souboru. Spouští se přírůstková kompilace...", @@ -461,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Inicializátor členu v deklaracích ambientního výčtu musí být konstantní výraz.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Ve výčtu s víc deklaracemi může být jenom u jedné deklarace vynechaný inicializátor u prvního elementu výčtu.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "V inicializátoru člena deklarací výčtu const musí být konstantní výraz.", + "Include_modules_imported_with_json_extension_6197": "Zahrnout moduly importované s příponou .json", "Index_signature_in_type_0_only_permits_reading_2542": "Signatura indexu v typu {0} povoluje jen čtení.", "Index_signature_is_missing_in_type_0_2329": "V typu {0} chybí signatura indexu.", "Index_signatures_are_incompatible_2330": "Signatury indexu jsou nekompatibilní.", @@ -559,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Název modulu {0} byl úspěšně přeložen na {1}. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Druh překladu modulu nebyl určen, použije se {0}.", "Module_resolution_using_rootDirs_has_failed_6111": "Překlad modulu pomocí rootDirs se nepovedl.", + "Move_to_a_new_file_95049": "Přesunout do nového souboru", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Více po sobě jdoucích číselných oddělovačů se nepovoluje.", "Multiple_constructor_implementations_are_not_allowed_2392": "Víc implementací konstruktoru se nepovoluje.", "NEWLINE_6061": "NOVÝ ŘÁDEK", @@ -600,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Možnost isolatedModules jde použít jenom v případě, že je poskytnutá možnost --module nebo že možnost target je ES2015 nebo vyšší verze.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Možnost paths se nedá použít bez zadání možnosti --baseUrl.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Možnost project se na příkazovém řádku nedá kombinovat se zdrojovým souborem.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Možnost --resolveJsonModule se nedá zadat bez strategie překladu modulu node.", "Options_Colon_6027": "Možnosti:", "Output_directory_for_generated_declaration_files_6166": "Výstupní adresář pro vygenerované soubory deklarace", + "Output_file_0_from_project_1_does_not_exist_6309": "Výstupní soubor {0} z projektu {1} neexistuje.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Výstupní soubor {0} se nesestavil ze zdrojového souboru {1}.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "Signatura přetížení není kompatibilní s implementací funkce.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Signatury přetížení musí být všechny abstraktní nebo neabstraktní.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Signatury přetížení musí být všechny ambientní nebo neambientní.", @@ -645,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Část kompilace, při které se vypisují názvy generovaných souborů", "Print_the_compiler_s_version_6019": "Vytisknout verzi kompilátoru", "Print_this_message_6017": "Vytisknout tuto zprávu", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odkazy projektu nemůžou tvořit cyklický graf. Zjistil se cyklus: {0}", + "Projects_to_reference_6300": "Projekty, které se mají odkazovat", "Property_0_does_not_exist_on_const_enum_1_2479": "Vlastnost {0} ve výčtu const {1} neexistuje.", "Property_0_does_not_exist_on_type_1_2339": "Vlastnost {0} v typu {1} neexistuje.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Vlastnost {0} v typu {1} neexistuje. Nezapomněli jste použít await?", @@ -692,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Vyvolat chybu u výrazů a deklarací s implikovaným typem any", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Vyvolá chybu u výrazů this s implikovaným typem any.", "Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Odkazovaný projekt {0} musí mít nastavení \"composite\": true.", + "Remove_all_unreachable_code_95051": "Odebrat veškerý nedosažitelný kód", "Remove_declaration_for_Colon_0_90004": "Odebrat deklaraci pro {0}", + "Remove_destructuring_90009": "Odebrat destrukci", "Remove_import_from_0_90005": "Odebrat import z {0}", + "Remove_unreachable_code_95050": "Odebrat nedosažitelný kód", "Replace_import_with_0_95015": "Nahradí import použitím: {0}.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Oznámí se chyba, když některé cesty kódu ve funkci nevracejí hodnotu.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Oznámí se chyby v případech fallthrough v příkazu switch.", @@ -801,6 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "Seznam files v konfiguračním souboru {0} je prázdný.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "První parametr metody then příslibu musí být zpětné volání.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Globální typ JSX.{0} by neměl mít více než jednu vlastnost.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Metavlastnost import.meta je povolená, jenom když se pro možnosti kompilátoru target a module použije ESNext.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Odvozený typ {0} odkazuje na nepřístupný typ {1}. Musí se použít anotace typu.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Levá strana příkazu for...in nemůže být destrukturačním vzorem.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Levá strana příkazu for...in nemůže používat anotaci typu.", @@ -1013,6 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Modifikátory parametrů se dají použít jenom v souboru .ts.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Je zadaná možnost paths, hledá se vzor, který odpovídá názvu modulu {0}.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modifikátor readonly se může objevit jenom v deklaraci vlastnosti nebo signatuře indexu.", + "require_call_may_be_converted_to_an_import_80005": "Volání require se dá převést na import.", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Je nastavená možnost rootDirs, použije se k překladu relativního názvu modulu {0}.", "super_can_only_be_referenced_in_a_derived_class_2335": "Na vlastnost super se dá odkazovat jenom v odvozené třídě.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Na možnost super je možné odkazovat jenom ve členech odvozených tříd nebo výrazů literálu objektu.", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 18ff646b374..61c5a4bc241 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Alle Deklarationen von \"{0}\" müssen identische Modifizierer aufweisen.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Alle Deklarationen von \"{0}\" müssen identische Typparameter aufweisen.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Alle Deklarationen einer abstrakten Methode müssen aufeinanderfolgend sein.", + "All_destructured_elements_are_unused_6198": "Alle destrukturierten Elemente werden nicht verwendet.", "All_imports_in_import_declaration_are_unused_6192": "Keiner der Importe in der Importdeklaration wird verwendet.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Standardimporte von Modulen ohne Standardexport zulassen. Dies wirkt sich nicht auf die Codeausgabe aus, lediglich auf die Typprüfung.", "Allow_javascript_files_to_be_compiled_6102": "Kompilierung von JavaScript-Dateien zulassen.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Ein Objekt, das möglicherweise NULL ist, kann nicht aufgerufen werden.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Ein Objekt, das möglicherweise NULL oder nicht definiert ist, kann nicht aufgerufen werden.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Ein Objekt, das möglicherweise nicht definiert ist, kann nicht aufgerufen werden.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Das Projekt \"{0}\" kann nicht vorgestellt werden, weil \"outFile\" nicht festgelegt wurde.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Ein Typ kann nicht erneut exportiert werden, wenn das Flag \"--isolatedModules\" angegeben ist.", "Cannot_read_file_0_Colon_1_5012": "Die Datei \"{0}\" kann nicht gelesen werden: {1}", "Cannot_redeclare_block_scoped_variable_0_2451": "Die blockbezogene Variable \"{0}\" Blockbereich kann nicht erneut deklariert werden.", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Kompilieren Sie das dem Pfad zugewiesene Projekt zu dessen Konfigurationsdatei oder zu einem Ordner mit der Datei \"tsconfig.json\".", "Compiler_option_0_expects_an_argument_6044": "Die Compileroption \"{0}\" erwartet ein Argument.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Die Compileroption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", + "Composite_projects_may_not_disable_declaration_emit_6304": "In zusammengesetzten Projekten kann die Deklarationsausgabe nicht deaktiviert werden.", "Computed_property_names_are_not_allowed_in_enums_1164": "Berechnete Eigenschaftennamen sind in Enumerationen unzulässig.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Berechnete Werte sind in einer Enumeration mit Membern mit Zeichenfolgenwerten nicht zulässig.", "Concatenate_and_emit_output_to_single_file_6001": "Verketten und Ausgabe in einer Datei speichern.", @@ -271,11 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktoren für abgeleitete Klassen müssen einen Aufruf \"super\" enthalten.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Die enthaltene Datei wird nicht angegeben, und das Stammverzeichnis kann nicht ermittelt werden. Die Suche im Ordner \"node_modules\" wird übersprungen.", "Convert_all_constructor_functions_to_classes_95045": "Alle Konstruktorfunktionen in Klassen konvertieren", - "Convert_all_require_to_import_95048": "Convert all 'require' to 'import'", + "Convert_all_require_to_import_95048": "Alle Aufrufe von \"require\" in \"import\" konvertieren", "Convert_all_to_default_imports_95035": "Alle in Standardimporte konvertieren", "Convert_function_0_to_class_95002": "Funktion \"{0}\" in Klasse konvertieren", "Convert_function_to_an_ES2015_class_95001": "Funktion in eine ES2015-Klasse konvertieren", - "Convert_require_to_import_95047": "Convert 'require' to 'import'", + "Convert_require_to_import_95047": "\"require\" in \"import\" konvertieren", "Convert_to_ES6_module_95017": "In ES6-Modul konvertieren", "Convert_to_default_import_95013": "In Standardimport konvertieren", "Corrupted_locale_file_0_6051": "Die Gebietsschemadatei \"{0}\" ist beschädigt.", @@ -328,8 +331,8 @@ "Duplicate_label_0_1114": "Doppelte Bezeichnung \"{0}\".", "Duplicate_number_index_signature_2375": "Doppelte Zahlenindexsignatur.", "Duplicate_string_index_signature_2374": "Doppelte Zeichenfolgen-Indexsignatur.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Der dynamische Import kann nicht verwendet werden, wenn ECMAScript 2015-Module das Ziel sind.", "Dynamic_import_cannot_have_type_arguments_1326": "Der dynamische Import kann nicht über Typargumente verfügen.", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Der dynamische Import wird nur unterstützt, wenn das Flag \"--module\" auf \"commonjs\" oder \"esNext\" festgelegt ist.", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Der dynamische Import benötigt einen Spezifizierer als Argument.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Der Spezifizierer des dynamischen Imports muss den Typ \"string\" aufweisen, hier ist er jedoch vom Typ \"{0}\".", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Das Element weist implizit einen Typ \"any\" auf, weil der Indexausdruck nicht vom Typ \"number\" ist.", @@ -338,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Geben Sie eine einzelne Datei mit Quellzuordnungen anstelle einer separaten Datei aus.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Geben Sie die Quelle zusammen mit den Quellzuordnungen innerhalb einer einzelnen Datei aus; hierfür muss \"--inlineSourceMap\" oder \"--sourceMap\" festgelegt sein.", "Enable_all_strict_type_checking_options_6180": "Aktivieren Sie alle strengen Typüberprüfungsoptionen.", + "Enable_project_compilation_6302": "Projektkompilierung aktivieren", "Enable_strict_checking_of_function_types_6186": "Aktivieren Sie die strenge Überprüfung für Funktionstypen.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Aktivieren Sie die strenge Überprüfung der Eigenschafteninitialisierung in Klassen.", "Enable_strict_null_checks_6113": "Strenge NULL-Überprüfungen aktivieren.", @@ -399,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Die Datei \"{0}\" hat eine nicht unterstützte Erweiterung und wird übersprungen.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Die Datei \"{0}\" weist eine nicht unterstützte Erweiterung auf. Die einzigen unterstützten Erweiterungen sind \"{1}\".", "File_0_is_not_a_module_2306": "Die Datei \"{0}\" ist kein Modul.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Die Datei \"{0}\" befindet sich nicht in der Liste der Projektdateien. Projekte müssen alle Dateien auflisten oder ein include-Muster verwenden.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Datei \"{0}\" befindet sich nicht unter \"rootDir\" \"{1}\". \"rootDir\" muss alle Quelldateien enthalten.", "File_0_not_found_6053": "Die Datei \"{0}\" wurde nicht gefunden.", "File_change_detected_Starting_incremental_compilation_6032": "Es wurde eine Dateiänderung erkannt. Die inkrementelle Kompilierung wird gestartet...", @@ -463,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "In Umgebungsenumerationsdeklarationen muss der Memberinitialisierer ein konstanter Ausdruck sein.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In einer Enumeration mit mehreren Deklarationen kann nur eine Deklaration einen Initialisierer für das erste Enumerationselement ausgeben.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "In const-Enumerationsdeklarationen muss der Memberinitialisierer ein konstanter Ausdruck sein.", + "Include_modules_imported_with_json_extension_6197": "Importierte Module mit der Erweiterung \"JSON\" einschließen", "Index_signature_in_type_0_only_permits_reading_2542": "Die Indexsignatur in Typ \"{0}\" lässt nur Lesevorgänge zu.", "Index_signature_is_missing_in_type_0_2329": "Die Indexsignatur fehlt im Typ \"{0}\".", "Index_signatures_are_incompatible_2330": "Die Indexsignaturen sind nicht kompatibel.", @@ -561,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Der Modulname \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Die Art der Modulauflösung wird nicht angegeben. \"{0}\" wird verwendet.", "Module_resolution_using_rootDirs_has_failed_6111": "Fehler bei der Modulauflösung mithilfe von \"rootDirs\".", + "Move_to_a_new_file_95049": "In neue Datei verschieben", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Mehrere aufeinander folgende numerische Trennzeichen sind nicht zulässig.", "Multiple_constructor_implementations_are_not_allowed_2392": "Mehrere Konstruktorimplementierungen sind unzulässig.", "NEWLINE_6061": "NEUE ZEILE", @@ -602,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Die Option \"isolatedModules\" kann nur verwendet werden, wenn entweder die Option \"--module\" angegeben ist oder die Option \"target\" den Wert \"ES2015\" oder höher aufweist.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Die \"path\"-Option kann nicht ohne Angabe der \"-baseUrl\"-Option angegeben werden.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Die Option \"project\" darf nicht mit Quelldateien in einer Befehlszeile kombiniert werden.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Die Option \"--resolveJsonModule\" kann nicht ohne die Modulauflösungsstrategie \"node\" angegeben werden.", "Options_Colon_6027": "Optionen:", "Output_directory_for_generated_declaration_files_6166": "Ausgabeverzeichnis für erstellte Deklarationsdateien.", + "Output_file_0_from_project_1_does_not_exist_6309": "Die Ausgabedatei \"{0}\" aus dem Projekt \"{1}\" ist nicht vorhanden.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Die Ausgabedatei \"{0}\" wurde nicht aus der Quelldatei \"{1}\" erstellt.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "Die Überladungssignatur ist nicht mit der Funktionsimplementierung kompatibel.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Überladungssignaturen müssen alle abstrakt oder nicht abstrakt sein.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Überladungssignaturen müssen alle umgebend oder nicht umgebend sein.", @@ -647,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Drucknamen des generierten Dateiteils der Kompilierung.", "Print_the_compiler_s_version_6019": "Die Version des Compilers ausgeben.", "Print_this_message_6017": "Diese Nachricht ausgeben.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Projektverweise dürfen keinen kreisförmigen Graphen bilden. Zyklus erkannt: {0}", + "Projects_to_reference_6300": "Zu referenzierende Projekte", "Property_0_does_not_exist_on_const_enum_1_2479": "Die Eigenschaft \"{0}\" ist für die const-Enumeration \"{1}\" nicht vorhanden.", "Property_0_does_not_exist_on_type_1_2339": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" nicht vorhanden. Haben Sie \"await\" nicht verwendet?", @@ -694,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Fehler für Ausdrücke und Deklarationen mit einem impliziten any-Typ auslösen.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Fehler für \"this\"-Ausdrücke mit einem impliziten any-Typ auslösen.", "Redirect_output_structure_to_the_directory_6006": "Die Ausgabestruktur in das Verzeichnis umleiten.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Das referenzierte Projekt \"{0}\" muss für die Einstellung \"composite\" den Wert TRUE aufweisen.", + "Remove_all_unreachable_code_95051": "Gesamten nicht erreichbaren Code entfernen", "Remove_declaration_for_Colon_0_90004": "Deklaration entfernen für: {0}", + "Remove_destructuring_90009": "Destrukturierung entfernen", "Remove_import_from_0_90005": "Import aus \"{0}\" entfernen", + "Remove_unreachable_code_95050": "Nicht erreichbaren Code entfernen", "Replace_import_with_0_95015": "Ersetzen Sie den Import durch \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Fehler melden, wenn nicht alle Codepfade in der Funktion einen Wert zurückgeben.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Für FallTrough-Fälle in switch-Anweisung Fehler melden.", @@ -803,7 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "Die Liste \"files\" in der Konfigurationsdatei \"{0}\" ist leer.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Der erste Parameter der \"then\"-Methode einer Zusage muss ein Rückruf sein.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Der globale Typ \"JSX.{0}\" darf nur eine Eigenschaft aufweisen.", - "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Die Metaeigenschaft \"import.meta\" ist nur bei Verwendung von \"ESNext\" für die Compileroptionen \"target\" und \"module\" zulässig.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Der abgeleitete Typ von \"{0}\" verweist auf einen Typ \"{1}\", auf den nicht zugegriffen werden kann. Eine Typanmerkung ist erforderlich.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Die linke Seite einer for...in-Anweisung darf kein Destrukturierungsmuster sein.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Die linke Seite einer for...in-Anweisung darf keine Typanmerkung verwenden.", @@ -1016,7 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" kann nur in einer TS-Datei verwendet werden.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Die Option \"paths\" wurde angegeben. Es wird nach einem Muster gesucht, das mit dem Modulnamen \"{0}\" übereinstimmt.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Der Modifizierer \"readonly\" darf nur für eine Eigenschaftendeklaration oder Indexsignatur verwendet werden.", - "require_call_may_be_converted_to_an_import_80005": "'require' call may be converted to an import.", + "require_call_may_be_converted_to_an_import_80005": "Der Aufruf von \"require\" kann in einen Aufruf von \"import\" konvertiert werden.", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Die Option \"rootDirs\" wurde festgelegt. Sie wird zum Auflösen des relativen Modulnamens \"{0}\" verwendet.", "super_can_only_be_referenced_in_a_derived_class_2335": "Auf \"super\" kann nur in einer abgeleiteten Klasse verwiesen werden.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Auf \"super\" kann nur in Membern abgeleiteter Klassen oder Objektliteralausdrücken verwiesen werden.", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg new file mode 100644 index 00000000000..3ea2129b89b --- /dev/null +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -0,0 +1,6398 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 7f708a3feeb..9d6ee4cc1f9 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"", "Add_initializers_to_all_uninitialized_properties_95027": "Agregar inicializadores a todas las propiedades sin inicializar", "Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta", + "Add_missing_typeof_95052": "Agregar el objeto typeof que falta", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Agregar un calificador a todas las variables no resueltas que coincidan con un nombre de miembro", "Add_to_all_uncalled_decorators_95044": "Agregar \"()\" a todos los elementos Decorator a los que no se llama", "Add_ts_ignore_to_all_error_messages_95042": "Agregar \"@ts-ignore\" a todos los mensajes de error", @@ -117,6 +118,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas las declaraciones de '{0}' deben tener modificadores idénticos.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas las declaraciones de '{0}' deben tener parámetros de tipo idénticos.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas las declaraciones de un método abstracto deben ser consecutivas.", + "All_destructured_elements_are_unused_6198": "Todos los elementos desestructurados están sin utilizar.", "All_imports_in_import_declaration_are_unused_6192": "Todas las importaciones de la declaración de importación están sin utilizar.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permitir las importaciones predeterminadas de los módulos sin exportación predeterminada. Esto no afecta a la emisión de código, solo a la comprobación de tipos.", "Allow_javascript_files_to_be_compiled_6102": "Permitir que se compilen los archivos de JavaScript.", @@ -220,6 +222,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "No se puede invocar un objeto que es posiblemente \"null\".", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "No se puede invocar un objeto que es posiblemente \"null\" o \"no definido\".", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "No se puede invocar un objeto que es posiblemente \"no definido\".", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "No se puede anteponer el proyecto \"{0}\" porque no se ha establecido \"outFile\".", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "No se puede volver a exportar un tipo si se proporciona la marca \"--isolatedModules\".", "Cannot_read_file_0_Colon_1_5012": "No se puede leer el archivo \"{0}\": {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "No se puede volver a declarar la variable con ámbito de bloque '{0}'.", @@ -260,6 +263,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila el proyecto teniendo en cuenta la ruta de acceso a su archivo de configuración o a una carpeta con un archivo \"tsconfig.json\".", "Compiler_option_0_expects_an_argument_6044": "La opción '{0}' del compilador espera un argumento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "La opción '{0}' del compilador requiere un valor de tipo {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Los proyectos compuestos no pueden deshabilitar la emisión de declaración.", "Computed_property_names_are_not_allowed_in_enums_1164": "No se permiten nombres de propiedad calculada en las enumeraciones.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "No se permiten valores calculados en una enumeración que tiene miembros con valores de cadena.", "Concatenate_and_emit_output_to_single_file_6001": "Concatenar y emitir la salida en un único archivo.", @@ -271,9 +275,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Los constructores de las clases derivadas deben contener una llamada a \"super\".", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "El archivo contenedor no se ha especificado y no se puede determinar el directorio raíz. Se omitirá la búsqueda en la carpeta 'node_modules'.", "Convert_all_constructor_functions_to_classes_95045": "Convertir todas las funciones de constructor en clases", + "Convert_all_require_to_import_95048": "Convertir todas las repeticiones de \"require\" en \"import\"", "Convert_all_to_default_imports_95035": "Convertir todo en importaciones predeterminadas", "Convert_function_0_to_class_95002": "Convertir la función \"{0}\" en una clase", "Convert_function_to_an_ES2015_class_95001": "Convertir la función en una clase ES2015", + "Convert_require_to_import_95047": "Convertir \"require\" en \"import\"", "Convert_to_ES6_module_95017": "Convertir en módulo ES6", "Convert_to_default_import_95013": "Convertir en importación predeterminada", "Corrupted_locale_file_0_6051": "Archivo de configuración regional {0} dañado.", @@ -326,8 +332,8 @@ "Duplicate_label_0_1114": "Etiqueta \"{0}\" duplicada.", "Duplicate_number_index_signature_2375": "Signatura de índice de número duplicada.", "Duplicate_string_index_signature_2374": "Signatura de índice de cadena duplicada.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "No se puede utilizar la importación dinámica cuando se destina a módulos ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "La importación dinámica no puede tener argumentos de tipo", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "La importación dinámica solo se admite cuando la marca \"--module\" es \"commonjs\" o \"esNext\".", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "La importación dinámica debe tener un especificador como argumento.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "El especificador de la importación dinámica debe ser de tipo \"string\", pero aquí tiene el tipo \"{0}\".", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "El elemento tiene un tipo 'any' implícito porque la expresión de índice no es de tipo 'number'.", @@ -336,6 +342,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir un solo archivo con mapas de origen en lugar de tener un archivo aparte.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir el origen junto a los mapas de origen en un solo archivo; requiere que se establezca \"--inlineSourceMap\" o \"--sourceMap\".", "Enable_all_strict_type_checking_options_6180": "Habilitar todas las opciones de comprobación de tipos estricta.", + "Enable_project_compilation_6302": "Habilitar la compilación de proyecto", "Enable_strict_checking_of_function_types_6186": "Habilite la comprobación estricta de los tipos de función.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite la comprobación estricta de inicialización de propiedades en las clases.", "Enable_strict_null_checks_6113": "Habilitar comprobaciones estrictas de elementos nulos.", @@ -397,6 +404,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "El archivo \"{0}\" tiene una extensión no admitida, así que se omitirá.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "La extensión del archivo '{0}' no es compatible. Las únicas extensiones compatibles son {1}.", "File_0_is_not_a_module_2306": "El archivo '{0}' no es un módulo.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "El archivo \"{0}\" no está en la lista de archivos del proyecto. Los proyectos deben enumerar todos los archivos o usar un patrón \"include\".", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "El archivo '{0}' no está en \"rootDir\" '{1}'. Se espera que \"rootDir\" contenga todos los archivos de origen.", "File_0_not_found_6053": "Archivo '{0}' no encontrado.", "File_change_detected_Starting_incremental_compilation_6032": "Se detectó un cambio de archivo. Iniciando la compilación incremental...", @@ -461,6 +469,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "En las declaraciones de enumeración de ambiente, el inicializador de miembro debe ser una expresión constante.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "En una enumeración con varias declaraciones, solo una declaración puede omitir un inicializador para el primer elemento de la enumeración.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "El inicializador de miembro de las declaraciones de enumeración \"const\" debe ser una expresión constante.", + "Include_modules_imported_with_json_extension_6197": "Incluir módulos importados con la extensión \".json\"", "Index_signature_in_type_0_only_permits_reading_2542": "La signatura de índice del tipo '{0}' solo permite lectura.", "Index_signature_is_missing_in_type_0_2329": "Falta la signatura de índice en el tipo '{0}'.", "Index_signatures_are_incompatible_2330": "Las signaturas de índice no son compatibles.", @@ -559,6 +568,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== El nombre del módulo '{0}' se resolvió correctamente como '{1}'. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "No se ha especificado el tipo de resolución del módulo, se usará '{0}'.", "Module_resolution_using_rootDirs_has_failed_6111": "No se pudo resolver el módulo con \"rootDirs\".", + "Move_to_a_new_file_95049": "Mover a un nuevo archivo", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "No se permiten varios separadores numéricos consecutivos.", "Multiple_constructor_implementations_are_not_allowed_2392": "No se permiten varias implementaciones del constructor.", "NEWLINE_6061": "NUEVA LÍNEA", @@ -600,8 +610,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "La opción \"isolatedModules\" solo se puede usar cuando se proporciona la opción \"--module\" o si la opción \"target\" es \"ES2015\" o una versión posterior.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "La opción 'paths' no se puede usar sin especificar la opción '--baseUrl'.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "La opción \"project\" no se puede combinar con archivos de origen en una línea de comandos.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "No se puede especificar la opción \"--resolveJsonModule\" sin la estrategia de resolución de módulos \"node\".", "Options_Colon_6027": "Opciones:", "Output_directory_for_generated_declaration_files_6166": "Directorio de salida para los archivos de declaración generados.", + "Output_file_0_from_project_1_does_not_exist_6309": "El archivo de salida \"{0}\" del proyecto \"{1}\" no existe.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "El archivo de salida \"{0}\" no se compiló desde el archivo de origen \"{1}\".", "Overload_signature_is_not_compatible_with_function_implementation_2394": "La signatura de sobrecarga no es compatible con la implementación de función.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Las signaturas de sobrecarga deben ser todas abstractas o no abstractas.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Las signaturas de sobrecarga deben ser todas de ambiente o de no ambiente.", @@ -645,6 +658,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimir los nombres de los archivos generados que forman parte de la compilación.", "Print_the_compiler_s_version_6019": "Imprima la versión del compilador.", "Print_this_message_6017": "Imprima este mensaje.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Las referencias del proyecto no pueden formar un gráfico circular. Ciclo detectado: {0}", + "Projects_to_reference_6300": "Proyectos a los que se hará referencia", "Property_0_does_not_exist_on_const_enum_1_2479": "La propiedad '{0}' no existe en la enumeración 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La propiedad '{0}' no existe en el tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Olvidó usar \"await\"?", @@ -692,8 +707,14 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Generar un error en las expresiones y las declaraciones con un tipo \"any\" implícito.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Generar un error en expresiones 'this' con un tipo 'any' implícito.", "Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "El proyecto \"{0}\" al que se hace referencia debe tener el valor \"composite\": true.", + "Remove_all_unreachable_code_95051": "Quitar todo el código inaccesible", + "Remove_all_unused_labels_95054": "Remove all unused labels", "Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\"", + "Remove_destructuring_90009": "Quitar la desestructuración", "Remove_import_from_0_90005": "Quitar importación de \"{0}\"", + "Remove_unreachable_code_95050": "Quitar el código inaccesible", + "Remove_unused_label_95053": "Remove unused label", "Replace_import_with_0_95015": "Reemplazar importación por \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Notificar errores de los casos de fallthrough en la instrucción switch.", @@ -801,7 +822,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "La lista de archivos del archivo de configuración '{0}' está vacía.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "El primer parámetro del método \"then\" de una promesa debe ser una devolución de llamada.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "El tipo \"JSX.{0}\" global no puede tener más de una propiedad.", - "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "La propiedad Meta \"import.meta\" solo se admite si se usa \"ESNext\" para las opciones del compilador \"target\" y \"module\".", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "El tipo inferido de \"{0}\" hace referencia a un tipo \"{1}\" no accesible. Se requiere una anotación de tipo.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte izquierda de una instrucción \"for...in\" no puede ser un patrón de desestructuración.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La parte izquierda de una instrucción \"for...in\" no puede usar una anotación de tipo.", @@ -1014,6 +1035,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" solo se puede usar en un archivo .ts.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Se ha especificado la opción 'paths'. Se buscará un patrón que coincida con el nombre de módulo '{0}'.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "El modificador 'readonly' solo puede aparecer en una declaración de propiedad o una signatura de índice.", + "require_call_may_be_converted_to_an_import_80005": "La llamada a \"require\" puede convertirse en una importación.", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Se ha establecido la opción \"rootDirs\". Se usará para resolver el nombre de módulo relativo \"{0}\".", "super_can_only_be_referenced_in_a_derived_class_2335": "Solo se puede hacer referencia a \"super\" en una clase derivada.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Solo se puede hacer referencia a 'super' en miembros de clases derivadas o expresiones de literal de objeto.", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 0280a35232d..23f0d175862 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "Ajouter un initialiseur à la propriété '{0}'", "Add_initializers_to_all_uninitialized_properties_95027": "Ajouter des initialiseurs à toutes les propriétés non initialisées", "Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'", + "Add_missing_typeof_95052": "Ajouter un typeof manquant", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Ajouter un qualificateur à toutes les variables non résolues correspondant à un nom de membre", "Add_to_all_uncalled_decorators_95044": "Ajouter '()' à tous les décorateurs non appelés", "Add_ts_ignore_to_all_error_messages_95042": "Ajouter '@ts-ignore' à tous les messages d'erreur", @@ -117,6 +118,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Toutes les déclarations de '{0}' doivent avoir des modificateurs identiques.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Toutes les déclarations de '{0}' doivent avoir des paramètres de type identiques.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Toutes les déclarations d'une méthode abstraite doivent être consécutives.", + "All_destructured_elements_are_unused_6198": "Tous les éléments déstructurés sont inutilisés.", "All_imports_in_import_declaration_are_unused_6192": "Les importations de la déclaration d'importation ne sont pas toutes utilisées.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Autorisez les importations par défaut à partir des modules sans exportation par défaut. Cela n'affecte pas l'émission du code, juste le contrôle de type.", "Allow_javascript_files_to_be_compiled_6102": "Autorisez la compilation des fichiers JavaScript.", @@ -220,6 +222,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Impossible d'appeler un objet qui a éventuellement une valeur 'null'.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Impossible d'appeler un objet qui a éventuellement une valeur 'null' ou 'undefined'.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Impossible d'appeler un objet qui a éventuellement une valeur 'undefined'.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Impossible de préfixer le projet '{0}', car 'outFile' n'est pas défini", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Impossible de réexporter un type quand l'indicateur '--isolatedModules' est spécifié.", "Cannot_read_file_0_Colon_1_5012": "Impossible de lire le fichier '{0}' : {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Impossible de redéclarer la variable de portée de bloc '{0}'.", @@ -260,6 +263,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compilez le projet en fonction du chemin de son fichier config ou d'un dossier contenant 'tsconfig.json'.", "Compiler_option_0_expects_an_argument_6044": "L'option de compilateur '{0}' attend an argument.", "Compiler_option_0_requires_a_value_of_type_1_5024": "L'option de compilateur '{0}' exige une valeur de type {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Les projets composites ne doivent pas désactiver l'émission de déclaration.", "Computed_property_names_are_not_allowed_in_enums_1164": "Les noms de propriétés calculées ne sont pas autorisés dans les enums.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Les valeurs calculées ne sont pas autorisées dans un enum avec des membres ayant une valeur de chaîne.", "Concatenate_and_emit_output_to_single_file_6001": "Concaténer la sortie et l'émettre vers un seul fichier.", @@ -271,9 +275,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Les constructeurs pour les classes dérivées doivent contenir un appel de 'super'.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Fichier conteneur non spécifié et répertoire racine impossible à déterminer. Recherche ignorée dans le dossier 'node_modules'.", "Convert_all_constructor_functions_to_classes_95045": "Convertir toutes les fonctions de constructeur en classes", + "Convert_all_require_to_import_95048": "Convertir tous les 'require' en 'import'", "Convert_all_to_default_imports_95035": "Convertir tout en importations par défaut", "Convert_function_0_to_class_95002": "Convertir la fonction '{0}' en classe", "Convert_function_to_an_ES2015_class_95001": "Convertir la fonction en classe ES2015", + "Convert_require_to_import_95047": "Convertir 'require' en 'import'", "Convert_to_ES6_module_95017": "Convertir en module ES6", "Convert_to_default_import_95013": "Convertir en importation par défaut", "Corrupted_locale_file_0_6051": "Fichier de paramètres régionaux endommagé : {0}.", @@ -326,8 +332,8 @@ "Duplicate_label_0_1114": "Étiquette '{0}' en double.", "Duplicate_number_index_signature_2375": "Signature d'index de nombre dupliquée.", "Duplicate_string_index_signature_2374": "Signature d'index de chaîne dupliquée.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "L'importation dynamique ne peut pas être utilisée pour cibler des modules ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "L'importation dynamique ne peut pas avoir d'arguments de type", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "L'importation dynamique est prise en charge uniquement quand l'indicateur '--module' a la valeur 'commonjs' ou 'esNext'.", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "L'importation dynamique doit avoir un seul spécificateur comme argument.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Le spécificateur de l'importation dynamique doit être de type 'string', mais ici il est de type '{0}'.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'élément possède implicitement un type 'any', car l'expression d'index n'est pas de type 'number'.", @@ -336,6 +342,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Émettez un seul fichier avec des mappages de sources au lieu d'avoir un fichier distinct.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Émettez la source aux côtés des mappages de sources dans un fichier unique. Nécessite la définition de '--inlineSourceMap' ou '--sourceMap'.", "Enable_all_strict_type_checking_options_6180": "Activez toutes les options de contrôle de type strict.", + "Enable_project_compilation_6302": "Activer la compilation du projet", "Enable_strict_checking_of_function_types_6186": "Activez la vérification stricte des types de fonction.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Activez la vérification stricte de l'initialisation des propriétés dans les classes.", "Enable_strict_null_checks_6113": "Activez strict null checks.", @@ -397,6 +404,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Le fichier '{0}' a une extension non prise en charge. Il est ignoré.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Le fichier '{0}' possède une extension non prise en charge. Les seules extensions prises en charge sont {1}.", "File_0_is_not_a_module_2306": "Le fichier '{0}' n'est pas un module.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Le fichier '{0}' ne figure pas dans la liste de fichiers projet. Les projets doivent lister tous les fichiers ou utiliser un modèle 'include'.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Le fichier '{0}' ne se trouve pas sous 'rootDir' '{1}'. 'rootDir' est supposé contenir tous les fichiers sources.", "File_0_not_found_6053": "Fichier '{0}' introuvable.", "File_change_detected_Starting_incremental_compilation_6032": "Modification de fichier détectée. Démarrage de la compilation incrémentielle...", @@ -461,6 +469,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Dans les déclarations d'enums ambiants, l'initialiseur de membre doit être une expression constante.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Dans un enum avec plusieurs déclarations, seule une déclaration peut omettre un initialiseur pour son premier élément d'enum.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Dans les déclarations d'enum 'const', l'initialiseur de membre doit être une expression constante.", + "Include_modules_imported_with_json_extension_6197": "Inclure les modules importés avec l'extension '.json'", "Index_signature_in_type_0_only_permits_reading_2542": "La signature d'index du type '{0}' autorise uniquement la lecture.", "Index_signature_is_missing_in_type_0_2329": "Signature d'index manquante dans le type '{0}'.", "Index_signatures_are_incompatible_2330": "Les signatures d'index sont incompatibles.", @@ -559,6 +568,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Le nom de module '{0}' a été correctement résolu en '{1}'. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Le genre de résolution de module n'est pas spécifié. Utilisation de '{0}'.", "Module_resolution_using_rootDirs_has_failed_6111": "Échec de la résolution de module à l'aide de 'rootDirs'.", + "Move_to_a_new_file_95049": "Déplacer vers un nouveau fichier", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Les séparateurs numériques consécutifs multiples ne sont pas autorisés.", "Multiple_constructor_implementations_are_not_allowed_2392": "Les implémentations de plusieurs constructeurs ne sont pas autorisées.", "NEWLINE_6061": "NOUVELLE LIGNE", @@ -600,8 +610,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'option 'isolatedModules' peut être utilisée seulement quand l'option '--module' est spécifiée, ou quand l'option 'target' a la valeur 'ES2015' ou une version supérieure.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Impossible d'utiliser l'option 'paths' sans spécifier l'option '--baseUrl'.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Impossible d'associer l'option 'project' à des fichiers sources sur une ligne de commande.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Impossible de spécifier l'option '--resolveJsonModule' sans la stratégie de résolution de module 'node'.", "Options_Colon_6027": "Options :", "Output_directory_for_generated_declaration_files_6166": "Répertoire de sortie pour les fichiers de déclaration générés.", + "Output_file_0_from_project_1_does_not_exist_6309": "Le fichier de sortie '{0}' du projet '{1}' n'existe pas", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Le fichier de sortie '{0}' n'a pas été créé à partir du fichier source '{1}'.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "La signature de surcharge n'est pas compatible avec l'implémentation de fonction.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Les signatures de surcharge doivent toutes être abstraites ou non abstraites.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Les signatures de surcharge doivent toutes être ambiantes ou non ambiantes.", @@ -645,6 +658,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimez les noms des fichiers générés faisant partie de la compilation.", "Print_the_compiler_s_version_6019": "Affichez la version du compilateur.", "Print_this_message_6017": "Imprimez ce message.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Les références de projet ne peuvent pas former un graphe circulaire. Cycle détecté : {0}", + "Projects_to_reference_6300": "Projets à référencer", "Property_0_does_not_exist_on_const_enum_1_2479": "La propriété '{0}' n'existe pas sur l'enum 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La propriété '{0}' n'existe pas sur le type '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La propriété '{0}' n'existe pas sur le type '{1}'. Avez-vous oublié d'utiliser 'await' ?", @@ -692,8 +707,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Lever une erreur sur les expressions et les déclarations ayant un type 'any' implicite.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Déclenche une erreur sur les expressions 'this' avec un type 'any' implicite.", "Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Le projet référencé '{0}' doit avoir le paramètre \"composite\" avec la valeur true.", + "Remove_all_unreachable_code_95051": "Supprimer tout le code inaccessible", "Remove_declaration_for_Colon_0_90004": "Supprimer la déclaration pour : '{0}'", + "Remove_destructuring_90009": "Supprimer la déstructuration", "Remove_import_from_0_90005": "Supprimer l'importation de '{0}'", + "Remove_unreachable_code_95050": "Supprimer le code inaccessible", "Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.", @@ -801,7 +820,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "La liste 'files' du fichier config '{0}' est vide.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Le premier paramètre de la méthode 'then' d'une promesse doit être un rappel.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Le type global 'JSX.{0}' ne peut pas avoir plusieurs propriétés.", - "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "La métapropriété 'import.meta' est uniquement autorisée avec 'ESNext' pour les options de compilateur 'target' et 'module'.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Le type déduit de '{0}' référence un type '{1}' inaccessible. Une annotation de type est nécessaire.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La partie gauche d'une instruction 'for...in' ne peut pas être un modèle de déstructuration.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La partie gauche d'une instruction 'for...in' ne peut pas utiliser d'annotation de type.", @@ -1014,6 +1033,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Les 'modificateurs de paramètre' peuvent uniquement être utilisés dans un fichier .ts.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "L'option 'paths' est spécifiée. Recherche d'un modèle correspondant au nom de module '{0}'.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Le modificateur 'readonly' peut apparaître uniquement dans une déclaration de propriété ou une signature d'index.", + "require_call_may_be_converted_to_an_import_80005": "L'appel de 'require' peut être converti en import.", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'option 'rootDirs' est définie. Utilisation de celle-ci pour la résolution du nom de module relatif '{0}'.", "super_can_only_be_referenced_in_a_derived_class_2335": "'super' ne peut être référencé que dans une classe dérivée.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' ne peut être référencé que dans les membres des classes dérivées ou les expressions littérales d'objet.", diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index 944f1979743..b7463e378ef 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Tutte le dichiarazioni di '{0}' devono contenere modificatori identici.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tutte le dichiarazioni di '{0}' devono contenere parametri di tipo identici.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Tutte le dichiarazioni di un metodo astratto devono essere consecutive.", + "All_destructured_elements_are_unused_6198": "Tutti gli elementi destrutturati sono inutilizzati.", "All_imports_in_import_declaration_are_unused_6192": "Tutte le importazioni nella dichiarazione di importazione sono inutilizzate.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Consente di eseguire importazioni predefinite da moduli senza esportazione predefinita. Non influisce sulla creazione del codice ma solo sul controllo dei tipi.", "Allow_javascript_files_to_be_compiled_6102": "Consente la compilazione di file JavaScript.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Non è possibile richiamare un oggetto che è probabilmente 'null'.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Non è possibile richiamare un oggetto che è probabilmente 'null' o 'undefined'.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Non è possibile richiamare un oggetto che è probabilmente 'undefined'.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Non è possibile anteporre il progetto '{0}' perché 'outFile' non è impostato", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Non è possibile riesportare un tipo quando è stato specificato il flag '--isolatedModules'.", "Cannot_read_file_0_Colon_1_5012": "Non è possibile leggere il file '{0}': {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Non è possibile dichiarare di nuovo la variabile con ambito blocco '{0}'.", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila il progetto in base al percorso del file di configurazione o della cartella contenente un file 'tsconfig.json'.", "Compiler_option_0_expects_an_argument_6044": "Con l'opzione '{0}' del compilatore è previsto un argomento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Con l'opzione '{0}' del compilatore è richiesto un valore di tipo {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "I progetti compositi non possono disabilitare la creazione di dichiarazioni.", "Computed_property_names_are_not_allowed_in_enums_1164": "I nomi di proprietà calcolati non sono consentiti nelle enumerazioni.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "In un'enumerazione con membri con valore stringa non sono consentiti valori calcolati.", "Concatenate_and_emit_output_to_single_file_6001": "Concatena e crea l'output in un singolo file.", @@ -271,9 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "I costruttori di classi derivate devono contenere una chiamata 'super'.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Il file contenitore non è specificato e non è possibile determinare la directory radice. La ricerca nella cartella 'node_modules' verrà ignorata.", "Convert_all_constructor_functions_to_classes_95045": "Convertire tutte le funzioni di costruttore in classi", + "Convert_all_require_to_import_95048": "Convertire tutte le occorrenze di 'require' in 'import'", "Convert_all_to_default_imports_95035": "Convertire tutte le impostazioni predefinite", "Convert_function_0_to_class_95002": "Converti la funzione '{0}' in classe", "Convert_function_to_an_ES2015_class_95001": "Converti la funzione in una classe ES2015", + "Convert_require_to_import_95047": "Convertire 'require' in 'import'", "Convert_to_ES6_module_95017": "Converti in modulo ES6", "Convert_to_default_import_95013": "Converti nell'importazione predefinita", "Corrupted_locale_file_0_6051": "Il file delle impostazioni locali {0} è danneggiato.", @@ -326,8 +331,8 @@ "Duplicate_label_0_1114": "Etichetta '{0}' duplicata.", "Duplicate_number_index_signature_2375": "La firma dell'indice di tipo number è duplicata.", "Duplicate_string_index_signature_2374": "La firma dell'indice di tipo string è duplicata.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Non è possibile usare l'importazione dinamica quando come destinazione si impostano moduli ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "Nell'importazione dinamica non possono essere presenti argomenti tipo", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "L'importazione dinamica è supportata solo quando il valore del flag '--module' è 'commonjs' o 'esNext'.", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Come argomento dell'importazione dinamica si può indicare un solo identificatore.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "L'identificatore dell'importazione dinamica deve essere di tipo 'string', ma il tipo specificato qui è '{0}'.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'elemento contiene implicitamente un tipo 'any' perché l'espressione di indice non è di tipo 'number'.", @@ -336,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Crea un unico file con i mapping di origine invece di file separati.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Crea l'origine unitamente alle mappe di origine all'interno di un unico file. Richiede l'impostazione di '--inlineSourceMap' o '--sourceMap'.", "Enable_all_strict_type_checking_options_6180": "Abilita tutte le opzioni per i controlli del tipo strict.", + "Enable_project_compilation_6302": "Abilitare la compilazione dei progetti", "Enable_strict_checking_of_function_types_6186": "Abilita il controllo tassativo dei tipi funzione.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Abilita il controllo tassativo dell'inizializzazione delle proprietà nelle classi.", "Enable_strict_null_checks_6113": "Abilita i controlli strict Null.", @@ -397,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "L'estensione del file '{0}' non è supportata. Il file verrà ignorato.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "L'estensione del file '{0}' non è supportata. Le uniche estensioni supportate sono {1}.", "File_0_is_not_a_module_2306": "Il file '{0}' non è un modulo.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Il file '{0}' non è presente nell'elenco dei file di progetto. I progetti devono elencare tutti i file o usare un criterio 'include'.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Il file '{0}' non si trova in 'rootDir' '{1}'. 'rootDir' deve contenere tutti i file di origine.", "File_0_not_found_6053": "Il file '{0}' non è stato trovato.", "File_change_detected_Starting_incremental_compilation_6032": "È stata rilevata una modifica ai file. Verrà avviata la compilazione incrementale...", @@ -461,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Nelle dichiarazioni di enumerazione dell'ambiente l'inizializzatore di membro deve essere un'espressione costante.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In un'enumerazione con più dichiarazioni solo una di queste può omettere un inizializzatore per il primo elemento dell'enumerazione.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Nelle dichiarazioni di enumerazione 'const' l'inizializzatore di membro deve essere un'espressione costante.", + "Include_modules_imported_with_json_extension_6197": "Includere i moduli importati con estensione '.json'", "Index_signature_in_type_0_only_permits_reading_2542": "La firma dell'indice nel tipo '{0}' consente solo la lettura.", "Index_signature_is_missing_in_type_0_2329": "Nel tipo '{0}' manca la firma dell'indice.", "Index_signatures_are_incompatible_2330": "Le firme dell'indice sono incompatibili.", @@ -559,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Il nome del modulo '{0}' è stato risolto in '{1}'. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Il tipo di risoluzione del modulo non è specificato. Verrà usato '{0}'.", "Module_resolution_using_rootDirs_has_failed_6111": "La risoluzione del modulo con 'rootDirs' non è riuscita.", + "Move_to_a_new_file_95049": "Passare a un nuovo file", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Non sono consentiti più separatori numerici consecutivi.", "Multiple_constructor_implementations_are_not_allowed_2392": "Non è possibile usare più implementazioni di costruttore.", "NEWLINE_6061": "NUOVA RIGA", @@ -600,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'opzione 'isolatedModules' può essere usata solo quando si specifica l'opzione '--module' oppure il valore dell'opzione 'target' è 'ES2015' o maggiore.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Non è possibile usare l'opzione 'paths' senza specificare l'opzione '--baseUrl'.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Non è possibile combinare l'opzione 'project' con file di origine in una riga di comando.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Non è possibile specificare l'opzione '--resolveJsonModule' senza la strategia di risoluzione del modulo 'node'.", "Options_Colon_6027": "Opzioni:", "Output_directory_for_generated_declaration_files_6166": "Directory di output per i file di dichiarazione generati.", + "Output_file_0_from_project_1_does_not_exist_6309": "Il file di output '{0}' del progetto '{1}' non esiste", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Il file di output '{0}' non è stato compilato dal file di origine '{1}'.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "La firma di overload non è compatibile con l'implementazione di funzione.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Le firme di overload devono essere tutte astratte o tutte non astratte.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Le firme di overload devono essere tutte di ambiente o non di ambiente.", @@ -645,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Stampa i nomi dei file generati che fanno parte della compilazione.", "Print_the_compiler_s_version_6019": "Stampa la versione del compilatore.", "Print_this_message_6017": "Stampa questo messaggio.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "I riferimenti al progetto non possono formare un grafico circolare. Ciclo rilevato: {0}", + "Projects_to_reference_6300": "Progetti cui fare riferimento", "Property_0_does_not_exist_on_const_enum_1_2479": "La proprietà '{0}' non esiste nell'enumerazione 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La proprietà '{0}' non esiste nel tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La proprietà '{0}' non esiste nel tipo '{1}'. Si è dimenticato di usare 'await'?", @@ -692,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Genera un errore in caso di espressioni o dichiarazioni con tipo 'any' implicito.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Genera un errore in caso di espressioni 'this con un tipo 'any' implicito.", "Redirect_output_structure_to_the_directory_6006": "Reindirizza la struttura di output alla directory.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Il progetto di riferimento '{0}' deve includere l'impostazione \"composite\": true.", + "Remove_all_unreachable_code_95051": "Rimuovere tutto il codice non eseguibile", "Remove_declaration_for_Colon_0_90004": "Rimuovere la dichiarazione per '{0}'", + "Remove_destructuring_90009": "Rimuovere la destrutturazione", "Remove_import_from_0_90005": "Rimuovere l'importazione da '{0}'", + "Remove_unreachable_code_95050": "Rimuovere il codice non eseguibile", "Replace_import_with_0_95015": "Sostituire l'importazione con '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Segnala l'errore quando non tutti i percorsi del codice nella funzione restituiscono un valore.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Segnala errori per i casi di fallthrough nell'istruzione switch.", @@ -801,6 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "L'elenco 'files' nel file config '{0}' è vuoto.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Il primo parametro del metodo 'then' di una promessa deve essere un callback.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Il tipo globale 'JSX.{0}' non può contenere più di una proprietà.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "La metaproprietà 'import.meta' è consentita solo se si usa 'ESNext' per le opzioni 'target' e 'module' del compilatore.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Il tipo dedotto di '{0}' fa riferimento a un tipo '{1}' non accessibile. È necessaria un'annotazione di tipo.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte sinistra di un'espressione 'for...in' non può essere un criterio di destrutturazione.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Nella parte sinistra di un'espressione 'for...in' non è possibile usare un'annotazione di tipo.", @@ -1013,6 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' può essere usato solo in un file con estensione ts.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "È specificata l'opzione 'paths'. Verrà cercato un criterio per la corrispondenza con il nome del modulo '{0}'.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Il modificatore 'readonly' può essere incluso solo in una dichiarazione di proprietà o una firma dell'indice.", + "require_call_may_be_converted_to_an_import_80005": "La chiamata a 'require' può essere convertita in un'importazione.", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'opzione 'rootDirs' è impostata e verrà usata per risolvere il nome del modulo relativo '{0}'.", "super_can_only_be_referenced_in_a_derived_class_2335": "È possibile fare riferimento a 'super' solo in una classe derivata.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "È possibile fare riferimento a 'super' solo in membri di classi derivate o espressioni letterali di oggetto.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index d82484ef79a..6189d07adce 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' のすべての宣言には、同一の修飾子が必要です。", "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' のすべての宣言には、同一の型パラメーターがある必要があります。", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象メソッドの宣言はすべて連続している必要があります。", + "All_destructured_elements_are_unused_6198": "非構造化要素はいずれも使用されていません。", "All_imports_in_import_declaration_are_unused_6192": "インポート宣言内のインポートはすべて未使用です。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "既定のエクスポートがないモジュールからの既定のインポートを許可します。これは、型チェックのみのため、コード生成には影響を与えません。", "Allow_javascript_files_to_be_compiled_6102": "javascript ファイルのコンパイルを許可します。", @@ -133,6 +134,7 @@ "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "非同期関数または非同期メソッドには、有効で待機可能な戻り値の型を指定する必要があります。", "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "非同期関数またはメソッドは 'Promise' を返す必要があります。'Promise' の宣言があること、または `--lib` オプションに 'ES2015' を含めていることを確認してください。", "An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。", + "An_element_access_expression_should_take_an_argument_1011": "要素アクセス式では、引数を取る必要があります。", "An_enum_member_cannot_have_a_numeric_name_2452": "列挙型メンバーに数値名を含めることはできません。", "An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの割り当てはモジュールでのみ使用可能です。", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの割り当ては、エクスポートされた他の要素を含むモジュールでは使用できません。", @@ -219,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null' の可能性があるオブジェクトを呼び出すことはできません。", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null' または 'undefined' の可能性があるオブジェクトを呼び出すことはできません。", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'undefined' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' が設定されていないため、プロジェクト '{0}' を先頭に追加することはできません", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "0'--isolatedModules' フラグが指定されている場合、型を再エクスポートできません。", "Cannot_read_file_0_Colon_1_5012": "ファイル '{0}' を読み取れません: {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "ブロック スコープの変数 '{0}' を再宣言することはできません。", @@ -259,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "構成ファイルか、'tsconfig.json' を含むフォルダーにパスが指定されたプロジェクトをコンパイルします。", "Compiler_option_0_expects_an_argument_6044": "コンパイラ オプション '{0}' には引数が必要です。", "Compiler_option_0_requires_a_value_of_type_1_5024": "コンパイラ オプション '{0}' には {1} の型の値が必要です。", + "Composite_projects_may_not_disable_declaration_emit_6304": "複合プロジェクトで宣言の生成を無効にすることはできません。", "Computed_property_names_are_not_allowed_in_enums_1164": "計算されたプロパティ名は列挙型では使用できません。", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "文字列値のメンバーを持つ列挙型では、計算値は許可されません。", "Concatenate_and_emit_output_to_single_file_6001": "出力を連結して 1 つのファイルを生成します。", @@ -270,9 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生クラスのコンストラクターには 'super' の呼び出しを含める必要があります。", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "包含するファイルが指定されていないため、ルート ディレクトリを決定できません。'node_modules' フォルダーのルックアップをスキップします。", "Convert_all_constructor_functions_to_classes_95045": "すべてのコンストラクター関数をクラスに変換します", + "Convert_all_require_to_import_95048": "'require' をすべて 'import' に変換", "Convert_all_to_default_imports_95035": "すべてを既定のインポートに変換します", "Convert_function_0_to_class_95002": "関数 '{0}' をクラスに変換します", "Convert_function_to_an_ES2015_class_95001": "関数を ES2015 クラスに変換します", + "Convert_require_to_import_95047": "'require' を 'import' に変換", "Convert_to_ES6_module_95017": "ES6 モジュールに変換します", "Convert_to_default_import_95013": "既定のインポートに変換する", "Corrupted_locale_file_0_6051": "ロケール ファイル {0} は破損しています。", @@ -325,8 +331,8 @@ "Duplicate_label_0_1114": "ラベル '{0}' が重複しています。", "Duplicate_number_index_signature_2375": "number インデックス シグネチャが重複しています。", "Duplicate_string_index_signature_2374": "string インデックス シグネチャが重複しています。", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 モジュールを対象とする場合、動的インポートを使用することはできません。", "Dynamic_import_cannot_have_type_arguments_1326": "動的インポートには型引数を指定することはできません", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "動的インポートがサポートされるのは、'--module' フラグが 'commonjs' または 'esNext' の場合のみです。", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動的インポートには、引数として 1 つの指定子を指定する必要があります。", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動的インポートの指定子の型は 'string' である必要がありますが、ここでは型 '{0}' が指定されています。", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "インデックス式が型 'number' ではないため、要素に 'any' 型が暗黙的に指定されます。", @@ -335,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "個々のファイルを持つ代わりに、複数のソース マップを含む単一ファイルを生成します。", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "単一ファイル内で sourcemap と共にソースを生成します。'--inlineSourceMap' または '--sourceMap' を設定する必要があります。", "Enable_all_strict_type_checking_options_6180": "厳密な型チェックのオプションをすべて有効にします。", + "Enable_project_compilation_6302": "プロジェクトのコンパイルを有効にします", "Enable_strict_checking_of_function_types_6186": "関数の型の厳密なチェックを有効にします。", "Enable_strict_checking_of_property_initialization_in_classes_6187": "クラス内のプロパティの初期化の厳密なチェックを有効にします。", "Enable_strict_null_checks_6113": "厳格な null チェックを有効にします。", @@ -396,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "ファイル '{0}' にはサポートされていない拡張機能があるため、スキップしています。", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "ファイル '{0}' はサポートされていない拡張子を含んでいます。サポートされている拡張子は {1} のみです。", "File_0_is_not_a_module_2306": "ファイル '{0}' はモジュールではありません。", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "ファイル '{0}' がプロジェクト ファイル リストに含まれていません。プロジェクトではすべてのファイルをリストするか、'include' パターンを使用する必要があります。", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "ファイル '{0}' が 'rootDir' '{1}' の下にありません。'rootDir' にすべてにソース ファイルが含まれている必要があります。", "File_0_not_found_6053": "ファイル '{0}' が見つかりません。", "File_change_detected_Starting_incremental_compilation_6032": "ファイルの変更が検出されました。インクリメンタル コンパイルを開始しています...", @@ -460,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "アンビエント列挙型の宣言では、メンバー初期化子は定数式である必要があります。", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "複数の宣言がある列挙型で、最初の列挙要素の初期化子を省略できる宣言は 1 つのみです。", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 列挙型の宣言で、メンバー初期化子は定数式でなければなりません。", + "Include_modules_imported_with_json_extension_6197": "'.json' 拡張子付きのインポートされたモジュールを含める", "Index_signature_in_type_0_only_permits_reading_2542": "型 '{0}' のインデックス シグネチャは、読み取りのみを許可します。", "Index_signature_is_missing_in_type_0_2329": "型 '{0}' のインデックス シグネチャがありません。", "Index_signatures_are_incompatible_2330": "インデックスの署名に互換性がありません。", @@ -558,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== モジュール名 '{0}' が正常に '{1}' に解決されました。========", "Module_resolution_kind_is_not_specified_using_0_6088": "モジュール解決の種類が '{0}' を使用して指定されていません。", "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' を使用したモジュール解決が失敗しました。", + "Move_to_a_new_file_95049": "新しいファイルへ移動します", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "複数の連続した数値区切り記号を指定することはできません。", "Multiple_constructor_implementations_are_not_allowed_2392": "コンストラクターを複数実装することはできません。", "NEWLINE_6061": "改行", @@ -599,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "オプション 'isolatedModules' は、オプション '--module' が指定されているか、オプション 'target' が 'ES2015' 以上であるかのいずれかの場合でのみ使用できます。", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "オプション 'paths' は、'--baseUrl' オプションを指定せずに使用できません。", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "オプション 'project' をコマンド ライン上でソース ファイルと一緒に指定することはできません。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' モジュールの解決方法を使用せずにオプション '--resolveJsonModule' を指定することはできません。", "Options_Colon_6027": "オプション:", "Output_directory_for_generated_declaration_files_6166": "生成された宣言ファイルの出力ディレクトリ。", + "Output_file_0_from_project_1_does_not_exist_6309": "プロジェクト '{1}' からの出力ファイル '{0}' がありません", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "出力ファイル '{0}' はソース ファイル '{1}' からビルドされていません。", "Overload_signature_is_not_compatible_with_function_implementation_2394": "オーバーロード シグネチャは関数の実装に対応していません。", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "オーバーロードのシグネチャはすべてが抽象または非抽象である必要があります。", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "オーバーロードのシグネチャは、すべてアンビエントであるか、すべてアンビエントでないかのどちらかである必要があります。", @@ -644,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "コンパイルの一環として生成されたファイル名を書き出します。", "Print_the_compiler_s_version_6019": "コンパイラのバージョンを表示します。", "Print_this_message_6017": "このメッセージを表示します。", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "プロジェクト参照が円グラフを形成できません。循環が検出されました: {0}", + "Projects_to_reference_6300": "参照するプロジェクト", "Property_0_does_not_exist_on_const_enum_1_2479": "プロパティ '{0}' が 'const' 列挙型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_2339": "プロパティ '{0}' は型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "型 '{1}' にプロパティ '{0}' は存在しません。'await' を使用していない可能性があります。", @@ -691,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "暗黙的な 'any' 型を含む式と宣言に関するエラーを発生させます。", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "暗黙的な 'any' 型を持つ 'this' 式でエラーが発生します。", "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "参照されているプロジェクト '{0}' には、設定 \"composite\": true が必要です。", + "Remove_all_unreachable_code_95051": "到達できないコードをすべて削除します", "Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除する: '{0}'", + "Remove_destructuring_90009": "非構造化を削除します", "Remove_import_from_0_90005": "'{0}' からのインポートを削除", + "Remove_unreachable_code_95050": "到達できないコードを削除します", "Replace_import_with_0_95015": "インポートを '{0}' に置換します。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "関数の一部のコード パスが値を返さない場合にエラーを報告します。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch ステートメントに case のフォールスルーがある場合にエラーを報告します。", @@ -701,7 +720,7 @@ "Report_errors_on_unused_parameters_6135": "使用されていないパラメーターに関するエラーを報告します。", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必須の型パラメーターの後に、オプションの型パラメーターを続けることはできません。", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "モジュール '{0}' の解決が場所 '{1}' のキャッシュに見つかりました。", - "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolve 'keyof' to string valued property names only (no numbers or symbols).", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'keyof' を文字列値のプロパティ名のみに解決します (数字または記号なし)。", "Resolving_from_node_modules_folder_6118": "node_modules フォルダーから解決しています...", "Resolving_module_0_from_1_6086": "======== '{1}' からモジュール '{0}' を解決しています。========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "ベース URL '{1}' - '{2}' に相対するモジュール名 '{0}' を解決しています。", @@ -800,6 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "'Import.meta' メタ プロパティでは、'target' および 'module' コンパイラ オプションに対して 'ESNext' のみが許可されています。", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' の推定型はアクセス不可能な '{1}' 型を参照します。型の注釈が必要です。", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' ステートメントの左側を非構造化パターンにすることはできません。", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' ステートメントの左側で型の注釈を使用することはできません。", @@ -947,6 +967,7 @@ "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' には型の注釈がなく、直接または間接的に初期化子で参照されているため、暗黙的に 'any' 型が含まれています。", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' はプリミティブですが、'{1}' はラッパー オブジェクトです。できれば '{0}' をご使用ください。", "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' が宣言されていますが、その値が読み取られることはありません。", + "_0_is_declared_but_never_used_6196": "'{0}' は宣言されましたが使用されませんでした。", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' はキーワード '{1}' に関するメタプロパティとして無効です。候補: '{2}'。", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' はそれ自身のベース式内で直接または間接的に参照されます。", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' はそれ自身の型の注釈内で直接または間接的に参照されます。", @@ -1011,6 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'パラメーター修飾子' を使用できるのは .ts ファイル内のみです。", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' オプションが指定され、モジュール名 '{0}' と一致するパターンを検索します。", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾子はプロパティ宣言またはインデックス シグネチャのみに使用できます。", + "require_call_may_be_converted_to_an_import_80005": "'require' の呼び出しはインポートに変換される可能性があります。", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' オプションが設定され、このオプションを使用して相対モジュール名 '{0}' を解決します。", "super_can_only_be_referenced_in_a_derived_class_2335": "'super' は、派生クラスでのみ参照できます。", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' は、派生クラスのメンバーまたはオブジェクトのリテラル式のメンバーでのみ参照されます。", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index 0065cb1ac94..9ab72b1379f 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}'의 모든 선언에는 동일한 한정자가 있어야 합니다.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}'의 모든 선언에는 동일한 형식 매개 변수가 있어야 합니다.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "추상 메서드의 모든 선언은 연속적이어야 합니다.", + "All_destructured_elements_are_unused_6198": "구조 파괴된 요소가 모두 사용되지 않습니다.", "All_imports_in_import_declaration_are_unused_6192": "가져오기 선언의 모든 가져오기가 사용되지 않습니다.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "기본 내보내기가 없는 모듈에서 기본 가져오기를 허용합니다. 여기서는 코드 내보내기에는 영향을 주지 않고 형식 검사만 합니다.", "Allow_javascript_files_to_be_compiled_6102": "Javascript 파일을 컴파일하도록 허용합니다.", @@ -133,6 +134,7 @@ "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "비동기 함수 또는 메서드에는 유효한 대기 가능 반환 형식이 있어야 합니다.", "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "비동기 함수 또는 메서드는 'Promise'를 반환해야 합니다. 'Promise'에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", "An_async_iterator_must_have_a_next_method_2519": "비동기 반복기에는 'next()' 메서드가 있어야 합니다.", + "An_element_access_expression_should_take_an_argument_1011": "요소 액세스 식은 인수를 사용해야 합니다.", "An_enum_member_cannot_have_a_numeric_name_2452": "열거형 멤버는 숫자 이름을 가질 수 없습니다.", "An_export_assignment_can_only_be_used_in_a_module_1231": "내보내기 할당은 모듈에서만 사용할 수 있습니다.", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "내보내기 할당은 다른 내보낸 요소가 있는 모듈에서 사용될 수 없습니다.", @@ -219,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null'이거나 '정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' 집합이 없기 때문에 '{0}' 프로젝트를 추가할 수 없습니다.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' 플래그가 제공된 경우 형식을 다시 내보낼 수 없습니다.", "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", @@ -259,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "구성 파일에 대한 경로 또는 'tsconfig.json'이 포함된 폴더에 대한 경로를 고려하여 프로젝트를 컴파일합니다.", "Compiler_option_0_expects_an_argument_6044": "컴파일러 옵션 '{0}'에는 인수가 필요합니다.", "Compiler_option_0_requires_a_value_of_type_1_5024": "컴파일러 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", + "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 사용하지 않도록 설정할 수 없습니다.", "Computed_property_names_are_not_allowed_in_enums_1164": "컴퓨팅된 속성 이름은 열거형에 사용할 수 없습니다.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "계산된 값은 문자열 값 멤버가 포함된 열거형에서 허용되지 않습니다.", "Concatenate_and_emit_output_to_single_file_6001": "출력을 연결하고 단일 파일로 내보냅니다.", @@ -270,9 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "파생 클래스의 생성자는 'super' 호출을 포함해야 합니다.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "포함 파일이 지정되지 않았고 루트 디렉터리를 확인할 수 없어 'node_modules' 폴더 조회를 건너뜁니다.", "Convert_all_constructor_functions_to_classes_95045": "모든 생성자 함수를 클래스로 변환", + "Convert_all_require_to_import_95048": "모든 'require'를 'import'로 변환", "Convert_all_to_default_imports_95035": "모든 항목을 기본 가져오기로 변환", "Convert_function_0_to_class_95002": "'{0}' 함수를 클래스로 변환", "Convert_function_to_an_ES2015_class_95001": "함수를 ES2015 클래스로 변환", + "Convert_require_to_import_95047": "'require'를 'import'로 변환", "Convert_to_ES6_module_95017": "ES6 모듈로 변환", "Convert_to_default_import_95013": "기본 가져오기로 변환", "Corrupted_locale_file_0_6051": "로캘 파일 {0}이(가) 손상되었습니다.", @@ -325,8 +331,8 @@ "Duplicate_label_0_1114": "중복된 레이블 '{0}'입니다.", "Duplicate_number_index_signature_2375": "중복 숫자 인덱스 시그니처입니다.", "Duplicate_string_index_signature_2374": "중복 문자열 인덱스 시그니처입니다.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 모듈을 대상을 지정할 때에는 동적 가져오기를 사용할 수 없습니다.", "Dynamic_import_cannot_have_type_arguments_1326": "동적 가져오기에는 형식 인수를 사용할 수 없습니다.", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "동적 가져오기는 '--module' 플래그가 'commonjs' 또는 'esNext'인 경우에만 지원됩니다.", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "동적 가져오기에는 지정자 하나를 인수로 사용해야 합니다.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "동적 가져오기의 지정자는 'string' 형식이어야 하지만 여기에서 형식은 '{0}'입니다.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "인덱스 식이 'number' 형식이 아니므로 요소에 암시적으로 'any' 형식이 있습니다.", @@ -335,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "별도의 파일을 사용하는 대신 소스 맵과 함께 단일 파일을 내보냅니다.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "단일 파일 내에서 소스 맵과 함께 소스를 내보냅니다. '--inlineSourceMap' 또는 '--sourceMap'을 설정해야 합니다.", "Enable_all_strict_type_checking_options_6180": "엄격한 형식 검사 옵션을 모두 사용하도록 설정합니다.", + "Enable_project_compilation_6302": "프로젝트 컴파일을 사용하도록 설정", "Enable_strict_checking_of_function_types_6186": "함수 형식에 대한 엄격한 검사를 사용하도록 설정합니다.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "클래스의 속성 초기화에 대해 엄격한 검사를 사용하도록 설정합니다.", "Enable_strict_null_checks_6113": "엄격한 null 검사를 사용하도록 설정하세요.", @@ -396,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "'{0}' 파일은 확장명이 지원되지 않으므로 건너뜁니다.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' 파일의 확장명이 지원되지 않습니다. 지원되는 확장명은 {1}뿐입니다.", "File_0_is_not_a_module_2306": "'{0}' 파일은 모듈이 아닙니다.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "'{0}' 파일이 프로젝트 파일 목록에 없습니다. 프로젝트는 모든 파일을 나열하거나 'include' 패턴을 사용해야 합니다.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' 파일이 'rootDir' '{1}' 아래에 있지 않습니다. 'rootDir'에는 모든 소스 파일이 포함되어 있어야 합니다.", "File_0_not_found_6053": "파일 '{0}'을(를) 찾을 수 없습니다.", "File_change_detected_Starting_incremental_compilation_6032": "파일 변경이 검색되었습니다. 증분 컴파일을 시작하는 중...", @@ -460,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "앰비언트 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "다중 선언이 포함된 열거형에서는 하나의 선언만 첫 번째 열거형 요소에 대한 이니셜라이저를 생략할 수 있습니다.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.", + "Include_modules_imported_with_json_extension_6197": "'.json' 확장을 사용하여 가져온 모듈을 포함합니다.", "Index_signature_in_type_0_only_permits_reading_2542": "'{0}' 형식의 인덱스 시그니처는 읽기만 허용됩니다.", "Index_signature_is_missing_in_type_0_2329": "'{0}' 형식에 인덱스 시그니처가 없습니다.", "Index_signatures_are_incompatible_2330": "인덱스 시그니처가 호환되지 않습니다.", @@ -558,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== 모듈 이름 '{0}'이(가) '{1}'(으)로 확인되었습니다. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "모듈 확인 종류가 지정되지 않았습니다. '{0}'을(를) 사용합니다.", "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs'를 사용한 모듈 확인에 실패했습니다.", + "Move_to_a_new_file_95049": "새 파일로 이동", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "여러 개의 연속된 숫자 구분 기호는 허용되지 않습니다.", "Multiple_constructor_implementations_are_not_allowed_2392": "여러 생성자 구현은 허용되지 않습니다.", "NEWLINE_6061": "줄 바꿈", @@ -599,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' 옵션은 '--module' 옵션을 지정하거나 'target' 옵션이 'ES2015' 이상인 경우에만 사용할 수 있습니다.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "'paths' 옵션은 '--baseUrl' 옵션을 지정하지 않고 사용할 수 없습니다.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "명령줄에서 'project' 옵션을 원본 파일과 혼합하여 사용할 수 없습니다.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' 모듈 확인 전략 없이 '--resolveJsonModule' 옵션을 지정할 수 없습니다.", "Options_Colon_6027": "옵션:", "Output_directory_for_generated_declaration_files_6166": "생성된 선언 파일의 출력 디렉터리입니다.", + "Output_file_0_from_project_1_does_not_exist_6309": "프로젝트 '{1}'의 출력 파일 '{0}'이(가) 존재하지 않습니다.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "출력 파일 '{0}'이(가) 소스 파일 '{1}'에서 빌드되지 않았습니다.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "오버로드 시그니처가 함수 구현과 호환되지 않습니다.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "오버로드 시그니처는 모두 추상이거나 비추상이어야 합니다.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "오버로드 시그니처는 모두 앰비언트이거나 앰비언트가 아니어야 합니다.", @@ -644,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", "Print_this_message_6017": "이 메시지를 출력합니다.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}", + "Projects_to_reference_6300": "참조할 프로젝트", "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 열거형 '{1}'에 '{0}' 속성이 없습니다.", "Property_0_does_not_exist_on_type_1_2339": "'{1}' 형식에 '{0}' 속성이 없습니다.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "속성 '{0}'이(가) '{1}' 형식에 없습니다. 'await' 사용을 잊으셨나요?", @@ -691,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "암시된 'any' 형식이 있는 식 및 선언에서 오류를 발생합니다.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.", "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "참조되는 프로젝트 '{0}'에는 \"composite\": true 설정이 있어야 합니다.", + "Remove_all_unreachable_code_95051": "접근할 수 없는 코드 모두 제거", "Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언 제거", + "Remove_destructuring_90009": "구조 파괴 제거", "Remove_import_from_0_90005": "'{0}'에서 가져오기 제거", + "Remove_unreachable_code_95050": "접근할 수 없는 코드 제거", "Replace_import_with_0_95015": "가져오기를 '{0}'(으)로 바꿉니다.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "함수의 일부 코드 경로가 값을 반환하지 않는 경우 오류를 보고합니다.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch 문의 fallthrough case에 대한 오류를 보고합니다.", @@ -701,7 +720,7 @@ "Report_errors_on_unused_parameters_6135": "사용되지 않은 매개 변수에 대한 오류를 보고합니다.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "필수 형식 매개 변수는 선택적 형식 매개 변수 다음에 올 수 없습니다.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' 모듈에 대한 해결을 '{1}' 위치의 캐시에서 찾았습니다.", - "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolve 'keyof' to string valued property names only (no numbers or symbols).", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "문자열 값 속성 이름에 대해서만 'keyof'를 확인합니다(숫자나 기호 아님).", "Resolving_from_node_modules_folder_6118": "node_modules 폴더에서 확인하는 중...", "Resolving_module_0_from_1_6086": "======== '{1}'에서 '{0}' 모듈을 확인하는 중입니다. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "기본 URL '{1}' - '{2}'을(를) 기준으로 모듈 이름 '{0}'을(를) 확인하는 중입니다.", @@ -800,6 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "'{0}' 구성 파일의 '파일' 목록이 비어 있습니다.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "프라미스에서 'then' 메서드의 첫 번째 매개 변수는 콜백이어야 합니다.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "전역 형식 'JSX.{0}'에 속성이 둘 이상 있을 수 없습니다.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "'import.meta' 메타 속성은 'target' 및 'module' 컴파일러 옵션에 'ESNext'를 사용해야만 허용됩니다.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}'의 유추 형식이 액세스할 수 없는 '{1}' 형식을 참조합니다. 형식 주석이 필요합니다.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 문의 왼쪽에는 구조 파괴 패턴을 사용할 수 없습니다.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 문의 왼쪽에는 형식 주석을 사용할 수 없습니다.", @@ -947,6 +967,7 @@ "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}'은(는) 형식 주석이 없고 자체 이니셜라이저에서 직간접적으로 참조되므로 암시적으로 'any' 형식입니다.", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0}'은(는) 기본 개체이지만 '{1}'은(는) 래퍼 개체입니다. 가능한 경우 '{0}'을(를) 사용하세요.", "_0_is_declared_but_its_value_is_never_read_6133": "'{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", + "_0_is_declared_but_never_used_6196": "'{0}'이(가) 선언되었지만 사용되지 않았습니다.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}'은(는) '{1}' 키워드에 대한 올바른 메타 속성이 아닙니다. '{2}'을(를) 사용하시겠습니까?", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}'은(는) 자체 기본 식에서 직간접적으로 참조됩니다.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}'은(는) 자체 형식 주석에서 직간접적으로 참조됩니다.", @@ -1011,6 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers'는 .ts 파일에서만 사용할 수 있습니다.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 옵션이 지정되었습니다. 모듈 이름 '{0}'과(와) 일치하는 패턴을 찾는 중입니다.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 한정자는 속성 선언 또는 인덱스 시그니처에만 나타날 수 있습니다.", + "require_call_may_be_converted_to_an_import_80005": "'require' 호출이 가져오기로 변환될 수 있습니다.", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 옵션이 설정되어 있습니다. 상대 모듈 이름 '{0}'을(를) 확인하려면 이 옵션을 사용합니다.", "super_can_only_be_referenced_in_a_derived_class_2335": "파생 클래스에서만 'super'를 참조할 수 있습니다.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "파생 클래스 또는 개체 리터럴 식의 멤버에서만 'super'를 참조할 수 있습니다.", diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 353672a04b3..c2f4120d683 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -94,6 +94,14 @@ declare function escape(string: string): string; */ declare function unescape(string: string): string; +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + declare type PropertyKey = string | number | symbol; interface PropertyDescriptor { @@ -20446,6 +20454,11 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * WSH is an alias for WScript under Windows Script Host + */ +declare var WSH: typeof WScript; + /** * Represents an Automation SAFEARRAY */ diff --git a/lib/lib.es2015.symbol.d.ts b/lib/lib.es2015.symbol.d.ts index a9cce33094b..bf09484d5fb 100644 --- a/lib/lib.es2015.symbol.d.ts +++ b/lib/lib.es2015.symbol.d.ts @@ -18,14 +18,6 @@ and limitations under the License. /// -interface Symbol { - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): symbol; -} - interface SymbolConstructor { /** * A reference to the prototype. diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index 25755653613..3d939b63e95 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -16302,6 +16302,11 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * WSH is an alias for WScript under Windows Script Host + */ +declare var WSH: typeof WScript; + /** * Represents an Automation SAFEARRAY */ diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index 2bd4a9324eb..5266bd3358f 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -16307,6 +16307,11 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * WSH is an alias for WScript under Windows Script Host + */ +declare var WSH: typeof WScript; + /** * Represents an Automation SAFEARRAY */ diff --git a/lib/lib.es2018.full.d.ts b/lib/lib.es2018.full.d.ts index d58edb260d8..9454d1e486b 100644 --- a/lib/lib.es2018.full.d.ts +++ b/lib/lib.es2018.full.d.ts @@ -16305,6 +16305,11 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * WSH is an alias for WScript under Windows Script Host + */ +declare var WSH: typeof WScript; + /** * Represents an Automation SAFEARRAY */ diff --git a/lib/lib.es2018.regexp.d.ts b/lib/lib.es2018.regexp.d.ts index a0017f21438..4ba698ff975 100644 --- a/lib/lib.es2018.regexp.d.ts +++ b/lib/lib.es2018.regexp.d.ts @@ -31,6 +31,9 @@ interface RegExpExecArray { } interface RegExp { - /** Returns a Boolean value indicating the state of the dotAll flag (s) used with a regular expression. Default is false. Read-only. */ + /** + * Returns a Boolean value indicating the state of the dotAll flag (s) used with a regular expression. + * Default is false. Read-only. + */ readonly dotAll: boolean; -} +} \ No newline at end of file diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 7126e31b52c..ac73e23d9f6 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -94,6 +94,14 @@ declare function escape(string: string): string; */ declare function unescape(string: string): string; +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + declare type PropertyKey = string | number | symbol; interface PropertyDescriptor { diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 8a00c1b800e..9ba2831332b 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -94,6 +94,14 @@ declare function escape(string: string): string; */ declare function unescape(string: string): string; +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; +} + declare type PropertyKey = string | number | symbol; interface PropertyDescriptor { @@ -5498,14 +5506,6 @@ declare namespace Reflect { } -interface Symbol { - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): symbol; -} - interface SymbolConstructor { /** * A reference to the prototype. @@ -22115,6 +22115,11 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * WSH is an alias for WScript under Windows Script Host + */ +declare var WSH: typeof WScript; + /** * Represents an Automation SAFEARRAY */ diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index 3f368fe0082..76d3c72b283 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -16304,6 +16304,11 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * WSH is an alias for WScript under Windows Script Host + */ +declare var WSH: typeof WScript; + /** * Represents an Automation SAFEARRAY */ diff --git a/lib/lib.scripthost.d.ts b/lib/lib.scripthost.d.ts index 149653a8971..5aab121c85f 100644 --- a/lib/lib.scripthost.d.ts +++ b/lib/lib.scripthost.d.ts @@ -221,6 +221,11 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * WSH is an alias for WScript under Windows Script Host + */ +declare var WSH: typeof WScript; + /** * Represents an Automation SAFEARRAY */ diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index c2922afa411..7a5316e7673 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Wszystkie deklaracje elementu „{0}” muszą mieć identyczne modyfikatory.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Wszystkie deklaracje „{0}” muszą mieć identyczne parametry typu.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Wszystkie deklaracje metody abstrakcyjnej muszą występować obok siebie.", + "All_destructured_elements_are_unused_6198": "Wszystkie elementy, których strukturę usunięto, są nieużywane.", "All_imports_in_import_declaration_are_unused_6192": "Wszystkie importy w deklaracji importu są nieużywane.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Zezwalaj na domyślne importy z modułów bez domyślnego eksportu. To nie wpływa na emitowanie kodu, a tylko na sprawdzanie typów.", "Allow_javascript_files_to_be_compiled_6102": "Zezwalaj na kompilowanie plików JavaScript.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null”.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null” lub „undefined”.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „undefined”.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Nie można poprzedzić projektu „{0}”, ponieważ nie ma on ustawionej właściwości „outFile”", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Nie można ponownie wyeksportować typu, jeśli podano flagę „--isolatedModules”", "Cannot_read_file_0_Colon_1_5012": "Nie można odczytać pliku „{0}”: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Nie można ponownie zadeklarować zmiennej „{0}” o zakresie bloku.", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Skompiluj projekt z uwzględnieniem ścieżki jego pliku konfiguracji lub folderu z plikiem „tsconfig.json”.", "Compiler_option_0_expects_an_argument_6044": "Opcja kompilatora „{0}” oczekuje argumentu.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Opcja kompilatora „{0}” wymaga wartości typu {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Projekty kompozytowe nie mogą wyłączyć emitowania deklaracji.", "Computed_property_names_are_not_allowed_in_enums_1164": "Obliczone nazwy właściwości nie są dozwolone w wyliczeniach.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Obliczone wartości nie są dozwolone w wyliczeniu ze składowymi o wartości ciągu.", "Concatenate_and_emit_output_to_single_file_6001": "Połącz i wyemituj dane wyjściowe do pojedynczego pliku.", @@ -271,9 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory klas pochodnych muszą zawierać wywołanie „super”.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Nie podano pliku zawierającego i nie można określić katalogu głównego. Pomijanie wyszukiwania w folderze „node_modules”.", "Convert_all_constructor_functions_to_classes_95045": "Przekonwertuj wszystkie funkcje konstruktora na klasy", + "Convert_all_require_to_import_95048": "Konwertuj wszystkie wywołania „require” na wywołania „import”", "Convert_all_to_default_imports_95035": "Przekonwertuj wszystko na domyślne importowanie", "Convert_function_0_to_class_95002": "Konwertuj funkcję „{0}” na klasę", "Convert_function_to_an_ES2015_class_95001": "Konwertuj funkcję na klasę ES2015", + "Convert_require_to_import_95047": "Konwertuj wywołanie „require” na wywołanie „import”", "Convert_to_ES6_module_95017": "Konwertuj na moduł ES6", "Convert_to_default_import_95013": "Konwertuj na import domyślny", "Corrupted_locale_file_0_6051": "Uszkodzony plik ustawień regionalnych {0}.", @@ -326,8 +331,8 @@ "Duplicate_label_0_1114": "Zduplikowana etykieta „{0}”.", "Duplicate_number_index_signature_2375": "Zduplikowana sygnatura indeksu liczbowego.", "Duplicate_string_index_signature_2374": "Zduplikowana sygnatura indeksu ciągu.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Nie można użyć dynamicznego importowania, gdy celem są moduły ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "Dynamiczne importowanie nie może mieć argumentów typu", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Import dynamiczny jest obsługiwany tylko wtedy, gdy flaga „--module” to „commonjs” lub „esNext”.", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dynamiczne importowanie musi mieć jeden specyfikator jako argument.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specyfikator dynamicznego importowania musi być typu „string”, ale określono typ „{0}”.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element niejawnie przyjmuje typ „any”, ponieważ wyrażenie indeksu ma typ inny niż „number”.", @@ -336,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emituj pojedynczy plik z mapami źródeł zamiast oddzielnego pliku.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emituj źródło razem z mapami źródłowymi w pojedynczym pliku; wymaga ustawienia opcji „--inlineSourceMap” lub „--sourceMap”.", "Enable_all_strict_type_checking_options_6180": "Włącz wszystkie opcje ścisłego sprawdzania typów.", + "Enable_project_compilation_6302": "Włącz kompilację projektu", "Enable_strict_checking_of_function_types_6186": "Włącz dokładne sprawdzanie typów funkcji.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Włącz dokładne sprawdzanie inicjowania właściwości w klasach.", "Enable_strict_null_checks_6113": "Włącz dokładne sprawdzanie wartości null.", @@ -397,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Plik „{0}” ma nieobsługiwane rozszerzenie, dlatego zostanie pominięty.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Plik „{0}” ma nieobsługiwane rozszerzenie. Obsługiwane są tylko rozszerzenia {1}.", "File_0_is_not_a_module_2306": "Plik „{0}” nie jest modułem.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Plik „{0}” nie znajduje się na liście plików projektu. Projekty muszą zawierać listę wszystkich plików lub używać wzorca „include”.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Plik „{0}” nie znajduje się w katalogu „rootDir” „{1}”. Katalog „rootDir” powinien zawierać wszystkie pliki źródłowe.", "File_0_not_found_6053": "Nie można odnaleźć pliku '{0}'.", "File_change_detected_Starting_incremental_compilation_6032": "Wykryto zmianę pliku. Trwa rozpoczynanie kompilacji przyrostowej...", @@ -461,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "W deklaracjach wyliczenia otoczenia inicjator składowej musi być wyrażeniem stałym.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "W przypadku wyliczenia z wieloma deklaracjami tylko jedna deklaracja może pominąć inicjator dla pierwszego elementu wyliczenia.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "W deklaracjach wyliczeń ze specyfikatorem „const” inicjator składowej musi być wyrażeniem stałym.", + "Include_modules_imported_with_json_extension_6197": "Uwzględnij moduły zaimportowane z rozszerzeniem „json”", "Index_signature_in_type_0_only_permits_reading_2542": "Sygnatura indeksu w typie „{0}” zezwala tylko na odczytywanie.", "Index_signature_is_missing_in_type_0_2329": "Brak sygnatury indeksu w typie „{0}”.", "Index_signatures_are_incompatible_2330": "Sygnatury indeksów są niezgodne.", @@ -559,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Nazwa modułu „{0}” została pomyślnie rozpoznana jako „{1}”. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Rodzaj rozpoznawania modułów nie został podany. Zostanie użyty rodzaj „{0}”.", "Module_resolution_using_rootDirs_has_failed_6111": "Nie można rozpoznać modułów przy użyciu opcji „rootDirs”.", + "Move_to_a_new_file_95049": "Przenieś do nowego pliku", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Kolejne następujące po sobie separatory liczbowe nie są dozwolone.", "Multiple_constructor_implementations_are_not_allowed_2392": "Konstruktor nie może mieć wielu implementacji.", "NEWLINE_6061": "NOWY WIERSZ", @@ -600,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Opcji „isolatedModules” można użyć tylko wtedy, gdy podano opcję „--module” lub opcja „target” określa cel „ES2015” lub wyższy.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Opcji „paths” nie można użyć bez podawania opcji „--baseUrl”.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Nie można mieszać opcji „project” z plikami źródłowymi w wierszu polecenia.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Nie można określić opcji „--resolveJsonModule” bez strategii rozpoznawania modułów „node”.", "Options_Colon_6027": "Opcje:", "Output_directory_for_generated_declaration_files_6166": "Katalog wyjściowy dla wygenerowanych plików deklaracji.", + "Output_file_0_from_project_1_does_not_exist_6309": "Plik wyjściowy „{0}” z projektu „{1}” nie istnieje", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Plik wyjściowy „{0}” nie został utworzony na podstawie pliku źródłowego „{1}”.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "Sygnatura przeciążenia nie jest zgodna z implementacją funkcji.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Wszystkie sygnatury przeciążeń muszą być abstrakcyjne lub nieabstrakcyjne.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Wszystkie sygnatury przeciążeń muszą być otaczającymi sygnaturami lub żadna nie może być otaczającą sygnaturą.", @@ -645,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Drukuj nazwy wygenerowanych plików będących częścią kompilacji.", "Print_the_compiler_s_version_6019": "Wypisz wersję kompilatora.", "Print_this_message_6017": "Wypisz ten komunikat.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odwołania do projektu nie mogą tworzyć grafu kołowego. Wykryto cykl: {0}", + "Projects_to_reference_6300": "Projekty do przywołania", "Property_0_does_not_exist_on_const_enum_1_2479": "Właściwość „{0}” nie istnieje w wyliczeniu ze specyfikatorem „const” „{1}”.", "Property_0_does_not_exist_on_type_1_2339": "Właściwość „{0}” nie istnieje w typie „{1}”.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy zapomniano użyć elementu „await”?", @@ -692,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Zgłaszaj błąd w przypadku wyrażeń i deklaracji z implikowanym typem „any”.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Zgłaszaj błąd w przypadku wyrażeń „this” z niejawnym typem „any”.", "Redirect_output_structure_to_the_directory_6006": "Przekieruj strukturę wyjściową do katalogu.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Przywoływany projekt „{0}” musi mieć ustawienie „composite” o wartości true.", + "Remove_all_unreachable_code_95051": "Usuń cały nieosiągalny kod", "Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”", + "Remove_destructuring_90009": "Usuń usuwanie struktury", "Remove_import_from_0_90005": "Usuń import z „{0}”", + "Remove_unreachable_code_95050": "Usuń nieosiągalny kod", "Replace_import_with_0_95015": "Zamień import na element „{0}”.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.", @@ -801,6 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "Lista „files” w pliku konfiguracji „{0}” jest pusta.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Pierwszym parametrem metody „then” obietnicy musi być wywołanie zwrotne.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Dla typu globalnego „JSX.{0}” nie można określić więcej niż jednej właściwości.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Metawłaściwość „import.meta” jest dozwolona tylko w przypadku podania wartości „ESNext” dla opcji kompilatora „target” i „module”.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Wnioskowany typ „{0}” przywołuje niedostępny typ „{1}”. Adnotacja typu jest konieczna.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Lewa strona instrukcji „for...in” nie może być wzorcem usuwającym strukturę.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Lewa strona instrukcji „for...in” nie może używać adnotacji typu.", @@ -1013,6 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Modyfikatorów parametrów można używać tylko w pliku ts.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Opcja „paths” została określona. Wyszukiwanie wzorca zgodnego z nazwą modułu „{0}”.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modyfikator „readonly” może występować jedynie w deklaracji właściwości lub sygnaturze indeksu.", + "require_call_may_be_converted_to_an_import_80005": "Wywołanie „require” może zostać przekonwertowane na wywołanie import.", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Opcja „rootDirs” została ustawiona. Zostanie ona użyta do rozpoznania względnej nazwy modułu „{0}”.", "super_can_only_be_referenced_in_a_derived_class_2335": "Element „super” może być przywoływany tylko w klasie pochodnej.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Element „super” może być przywoływany jedynie w składowych klas pochodnych lub wyrażeń literałów obiektów.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts new file mode 100644 index 00000000000..dc13cb5f575 --- /dev/null +++ b/lib/protocol.d.ts @@ -0,0 +1,2386 @@ +/** + * Declaration module describing the TypeScript Server protocol + */ +declare namespace ts.server.protocol { + const enum CommandTypes { + Brace = "brace", + BraceCompletion = "braceCompletion", + GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", + Change = "change", + Close = "close", + Completions = "completions", + CompletionDetails = "completionEntryDetails", + CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", + CompileOnSaveEmitFile = "compileOnSaveEmitFile", + Configure = "configure", + Definition = "definition", + DefinitionAndBoundSpan = "definitionAndBoundSpan", + Implementation = "implementation", + Exit = "exit", + Format = "format", + Formatonkey = "formatonkey", + Geterr = "geterr", + GeterrForProject = "geterrForProject", + SemanticDiagnosticsSync = "semanticDiagnosticsSync", + SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", + NavBar = "navbar", + Navto = "navto", + NavTree = "navtree", + NavTreeFull = "navtree-full", + /** @deprecated */ + Occurrences = "occurrences", + DocumentHighlights = "documentHighlights", + Open = "open", + Quickinfo = "quickinfo", + References = "references", + Reload = "reload", + Rename = "rename", + Saveto = "saveto", + SignatureHelp = "signatureHelp", + Status = "status", + TypeDefinition = "typeDefinition", + ProjectInfo = "projectInfo", + ReloadProjects = "reloadProjects", + Unknown = "unknown", + OpenExternalProject = "openExternalProject", + OpenExternalProjects = "openExternalProjects", + CloseExternalProject = "closeExternalProject", + GetOutliningSpans = "getOutliningSpans", + TodoComments = "todoComments", + Indentation = "indentation", + DocCommentTemplate = "docCommentTemplate", + CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", + GetCodeFixes = "getCodeFixes", + GetCombinedCodeFix = "getCombinedCodeFix", + ApplyCodeActionCommand = "applyCodeActionCommand", + GetSupportedCodeFixes = "getSupportedCodeFixes", + GetApplicableRefactors = "getApplicableRefactors", + GetEditsForRefactor = "getEditsForRefactor", + OrganizeImports = "organizeImports", + GetEditsForFileRename = "getEditsForFileRename" + } + /** + * A TypeScript Server message + */ + interface Message { + /** + * Sequence number of the message + */ + seq: number; + /** + * One of "request", "response", or "event" + */ + type: "request" | "response" | "event"; + } + /** + * Client-initiated request message + */ + interface Request extends Message { + type: "request"; + /** + * The command to execute + */ + command: string; + /** + * Object containing arguments for the command + */ + arguments?: any; + } + /** + * Request to reload the project structure for all the opened files + */ + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + /** + * Server-initiated event message + */ + interface Event extends Message { + type: "event"; + /** + * Name of event + */ + event: string; + /** + * Event-specific information + */ + body?: any; + } + /** + * Response by server to client request message. + */ + interface Response extends Message { + type: "response"; + /** + * Sequence number of the request message. + */ + request_seq: number; + /** + * Outcome of the request. + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. + */ + message?: string; + /** + * Contains message body if success === true. + */ + body?: any; + } + /** + * Arguments for FileRequest messages. + */ + interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ + file: string; + projectFileName?: string; + } + interface StatusRequest extends Request { + command: CommandTypes.Status; + } + interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ + version: string; + } + /** + * Response to StatusRequest + */ + interface StatusResponse extends Response { + body: StatusResponseBody; + } + /** + * Requests a JS Doc comment template for a given position + */ + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + /** + * Response to DocCommentTemplateRequest + */ + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** + * A request to get TODO comments from the file + */ + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + /** + * Arguments for TodoCommentRequest request. + */ + interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ + descriptors: TodoCommentDescriptor[]; + } + /** + * Response for TodoCommentRequest request. + */ + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + /** + * A request to determine if the caret is inside a comment. + */ + interface SpanOfEnclosingCommentRequest extends FileLocationRequest { + command: CommandTypes.GetSpanOfEnclosingComment; + arguments: SpanOfEnclosingCommentRequestArgs; + } + interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { + /** + * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. + */ + onlyMultiLine: boolean; + } + /** + * Request to obtain outlining spans in file. + */ + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.GetOutliningSpans; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + /** + * Response to OutliningSpansRequest request. + */ + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + /** + * A request to get indentation for a location in file + */ + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + /** + * Response for IndentationRequest request. + */ + interface IndentationResponse extends Response { + body?: IndentationResult; + } + /** + * Indentation result representing where indentation should be placed + */ + interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** + * Arguments for IndentationRequest request. + */ + interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ + options?: EditorSettings; + } + /** + * Arguments for ProjectInfoRequest request. + */ + interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + /** + * A request to get the project information of the current file. + */ + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + /** + * A request to retrieve compiler options diagnostics for a project + */ + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ + interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ + projectFileName: string; + } + /** + * Response message body for "projectInfo" request + */ + interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; + } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ + reportsUnnecessary?: {}; + } + /** + * Response message for "projectInfo" request + */ + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** + * Request whose sole parameter is a file name. + */ + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ + interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + line: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; + } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + /** + * Request refactorings at a given position or selection area. + */ + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + /** + * Response is a list of available refactorings. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ + interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ + name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ + description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; + } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + } + interface GetEditsForRefactorRequest extends Request { + command: CommandTypes.GetEditsForRefactor; + arguments: GetEditsForRefactorRequestArgs; + } + /** + * Request the edits that a particular refactoring action produces. + * Callers must specify the name of the refactor and the name of the action. + */ + type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { + refactor: string; + action: string; + }; + interface GetEditsForRefactorResponse extends Response { + body?: RefactorEditInfo; + } + interface RefactorEditInfo { + edits: FileCodeEdits[]; + /** + * An optional location where the editor should start a rename operation once + * the refactoring edits have been applied + */ + renameLocation?: Location; + renameFilename?: string; + } + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + interface OrganizeImportsRequest extends Request { + command: CommandTypes.OrganizeImports; + arguments: OrganizeImportsRequestArgs; + } + type OrganizeImportsScope = GetCombinedCodeFixScope; + interface OrganizeImportsRequestArgs { + scope: OrganizeImportsScope; + } + interface OrganizeImportsResponse extends Response { + edits: ReadonlyArray; + } + interface GetEditsForFileRenameRequest extends Request { + command: CommandTypes.GetEditsForFileRename; + arguments: GetEditsForFileRenameRequestArgs; + } + interface GetEditsForFileRenameRequestArgs extends FileRequestArgs { + readonly oldFilePath: string; + readonly newFilePath: string; + } + interface GetEditsForFileRenameResponse extends Response { + edits: ReadonlyArray; + } + /** + * Request for the available codefixes at a specific position. + */ + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + interface GetCombinedCodeFixRequest extends Request { + command: CommandTypes.GetCombinedCodeFix; + arguments: GetCombinedCodeFixRequestArgs; + } + interface GetCombinedCodeFixResponse extends Response { + body: CombinedCodeActions; + } + interface ApplyCodeActionCommandRequest extends Request { + command: CommandTypes.ApplyCodeActionCommand; + arguments: ApplyCodeActionCommandRequestArgs; + } + interface ApplyCodeActionCommandResponse extends Response { + } + interface FileRangeRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + startOffset: number; + /** + * The line number for the request (1-based). + */ + endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + endOffset: number; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRangeRequestArgs { + /** + * Errorcodes we want to get the fixes for. + */ + errorCodes?: ReadonlyArray; + } + interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; + } + interface ApplyCodeActionCommandRequestArgs { + /** May also be an array of commands. */ + command: {}; + } + /** + * Response for GetCodeFixes request. + */ + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** + * A request whose arguments specify a file location (file, line, col). + */ + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + /** + * A request to get codes of supported code fixes. + */ + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + } + /** + * A response for GetSupportedCodeFixesRequest request. + */ + interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; + } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + /** + * Location in source code expressed as (one-based) line and (one-based) column offset. + */ + interface Location { + line: number; + offset: number; + } + /** + * Object found in response messages defining a span of text in source code. + */ + interface TextSpan { + /** + * First character of the definition. + */ + start: Location; + /** + * One character past last character of the definition. + */ + end: Location; + } + /** + * Object found in response messages defining a span of text in a specific source file. + */ + interface FileSpan extends TextSpan { + /** + * File containing text span. + */ + file: string; + } + interface DefinitionInfoAndBoundSpan { + definitions: ReadonlyArray; + textSpan: TextSpan; + } + /** + * Definition response message. Gives text range for definition. + */ + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + interface DefinitionInfoAndBoundSpanReponse extends Response { + body?: DefinitionInfoAndBoundSpan; + } + /** + * Definition response message. Gives text range for definition. + */ + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Implementation response message. Gives text range for implementations. + */ + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + /** + * Request to get brace completion for a location in the file. + */ + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + /** + * Argument for BraceCompletionRequest request. + */ + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ + openingBrace: string; + } + /** + * @deprecated + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + /** @deprecated */ + interface OccurrencesResponseItem extends FileSpan { + /** + * True if the occurrence is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if the occurrence is in a string, undefined otherwise; + */ + isInString?: true; + } + /** @deprecated */ + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + */ + interface HighlightSpan extends TextSpan { + kind: HighlightSpanKind; + } + /** + * Represents a set of highligh spans for a give name + */ + interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ + file: string; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; + } + /** + * Response for a DocumentHighlightsRequest request. + */ + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ + lineText: string; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if reference is a definition, false otherwise. + */ + isDefinition: boolean; + } + /** + * The body of a "references" response message. + */ + interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: ReferencesResponseItem[]; + /** + * The name of the symbol. + */ + symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; + } + /** + * Response to "references" request. + */ + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + /** + * Argument for RenameRequest request. + */ + interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ + findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ + findInStrings?: boolean; + } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + /** + * Information about the item to be renamed. + */ + interface RenameInfo { + /** + * True if item can be renamed. + */ + canRename: boolean; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage?: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + } + /** + * A group of text spans, all in 'file'. + */ + interface SpanGroup { + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: TextSpan[]; + } + interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ + info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: ReadonlyArray; + } + /** + * Rename response message. + */ + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicitly. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ + interface ExternalFile { + /** + * Name of file file + */ + fileName: string; + /** + * Script kind of the file + */ + scriptKind?: ScriptKindName | ts.ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ + hasMixedContent?: boolean; + /** + * Content of the file + */ + content?: string; + } + /** + * Represent an external project + */ + interface ExternalProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of root files in project + */ + rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ + options: ExternalProjectCompilerOptions; + /** + * @deprecated typingOptions. Use typeAcquisition instead + */ + typingOptions?: TypeAcquisition; + /** + * Explicitly specified type acquisition for the project + */ + typeAcquisition?: TypeAcquisition; + } + interface CompileOnSaveMixin { + /** + * If compile on save is enabled for the project + */ + compileOnSave?: boolean; + } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; + /** + * Represents a set of changes that happen in project + */ + interface ProjectChanges { + /** + * List of added files + */ + added: string[]; + /** + * List of removed files + */ + removed: string[]; + /** + * List of updated files + */ + updated: string[]; + } + /** + * Information found in a configure request. + */ + interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatCodeSettings; + preferences?: UserPreferences; + /** + * The host's additional supported .js file extensions + */ + extraFileExtensions?: FileExtensionInfo[]; + } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ConfigureResponse extends Response { + } + /** + * Information found in an "open" request. + */ + interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: ScriptKindName; + /** + * Used to limit the searching for project config file. If given the searching will stop at this + * root path; otherwise it will go all the way up to the dist root path. + */ + projectRootPath?: string; + } + type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + /** + * Request to open or update external project + */ + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + /** + * Arguments to OpenExternalProjectRequest request + */ + type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + /** + * Arguments to OpenExternalProjectsRequest + */ + interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ + projects: ExternalProject[]; + } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectResponse extends Response { + } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectsResponse extends Response { + } + /** + * Request to close external project. + */ + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + /** + * Arguments to CloseExternalProjectRequest request + */ + interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ + projectFileName: string; + } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface CloseExternalProjectResponse extends Response { + } + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ + interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ + options: ExternalProjectCompilerOptions; + /** + * Specifies the project root path used to scope compiler options. + * It is an error to provide this property if the server has not been started with + * `useInferredProjectPerProjectRoot` enabled. + */ + projectRootPath?: string; + } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + /** + * Contains a list of files that should be regenerated in a project + */ + interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of files names that should be recompiled + */ + fileNames: string[]; + /** + * true if project uses outFile or out compiler option + */ + projectUsesOutFile: boolean; + } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ + forced?: boolean; + } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + /** + * Body of QuickInfoResponse. + */ + interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Starting file location of symbol. + */ + start: Location; + /** + * One past last character of symbol. + */ + end: Location; + /** + * Type and kind of symbol. + */ + displayString: string; + /** + * Documentation associated with symbol. + */ + documentation: string; + /** + * JSDoc tags associated with symbol. + */ + tags: JSDocTagInfo[]; + } + /** + * Quickinfo response message. + */ + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + /** + * Arguments for format messages. + */ + interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ + endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; + /** + * Format options to be used. + */ + options?: FormatCodeSettings; + } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ + interface CodeEdit { + /** + * First character of the text span to edit. + */ + start: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + /** The code actions that are available */ + body?: CodeFixAction[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ + commands?: {}[]; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands?: ReadonlyArray<{}>; + } + interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ + fixName: string; + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + /** Should be present if and only if 'fixId' is. */ + fixAllDescription?: string; + } + /** + * Format and format on key response message. + */ + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + /** + * Arguments for format on key messages. + */ + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; + options?: FormatCodeSettings; + } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; + /** + * Arguments for completions messages. + */ + interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; + triggerCharacter?: CompletionsTriggerCharacter; + /** + * @deprecated Use UserPreferences.includeCompletionsForModuleExports + */ + includeExternalModuleExports?: boolean; + /** + * @deprecated Use UserPreferences.includeCompletionsWithInsertText + */ + includeInsertTextCompletions?: boolean; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; + arguments: CompletionsRequestArgs; + } + /** + * Arguments for completion details request. + */ + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: (string | CompletionEntryIdentifier)[]; + } + interface CompletionEntryIdentifier { + name: string; + source: string; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + /** + * Part of a symbol description. + */ + interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + } + /** + * An item found in a completion response. + */ + interface CompletionEntry { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ + replacementSpan?: TextSpan; + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ + hasAction?: true; + /** + * Identifier (not necessarily human-readable) identifying where this completion came from. + */ + source?: string; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ + isRecommended?: true; + } + /** + * Additional completion entry details, available on demand + */ + interface CompletionEntryDetails { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ + documentation: SymbolDisplayPart[]; + /** + * JSDoc tags for the symbol. + */ + tags: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ + codeActions?: CodeAction[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + source?: SymbolDisplayPart[]; + } + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + /** + * Signature help information for a single parameter + */ + interface SignatureHelpParameter { + /** + * The parameter's name + */ + name: string; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + */ + interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; + /** + * The signature's JSDoc tags + */ + tags: JSDocTagInfo[]; + } + /** + * Signature help items found in the response of a signature help request. + */ + interface SignatureHelpItems { + /** + * The signature help items. + */ + items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; + /** + * The argument count + */ + argumentCount: number; + } + /** + * Arguments of a signature help request. + */ + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + /** + * Response object for a SignatureHelpRequest. + */ + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + /** + * Synchronous request for semantic diagnostics of one file. + */ + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous sematic diagnostics request. + */ + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface SuggestionDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SuggestionDiagnosticsSync; + arguments: SuggestionDiagnosticsSyncRequestArgs; + } + type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; + type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; + /** + * Synchronous request for syntactic diagnostics of one file. + */ + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous syntactic diagnostics request. + */ + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Arguments for GeterrForProject request. + */ + interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ + file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + /** + * Arguments for geterr messages. + */ + interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + type RequestCompletedEventName = "requestCompleted"; + /** + * Event that is sent when server have finished processing request with specified id. + */ + interface RequestCompletedEvent extends Event { + event: RequestCompletedEventName; + body: RequestCompletedEventBody; + } + interface RequestCompletedEventBody { + request_seq: number; + } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ + interface Diagnostic { + /** + * Starting file location at which text applies. + */ + start: Location; + /** + * The last file location at which the text applies. + */ + end: Location; + /** + * Text of diagnostic message. + */ + text: string; + /** + * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". + */ + category: string; + reportsUnnecessary?: {}; + /** + * The error code of the diagnostic message. + */ + code?: number; + /** + * The name of the plugin reporting the message. + */ + source?: string; + } + interface DiagnosticWithFileName extends Diagnostic { + /** + * Name of the file the diagnostic is in + */ + fileName: string; + } + interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ + file: string; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; + } + type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag"; + /** + * Event message for DiagnosticEventKind event types. + * These events provide syntactic and semantic errors for a file. + */ + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + } + interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; + /** + * The name of the found config file. + */ + configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: DiagnosticWithFileName[]; + } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + interface ProjectLanguageServiceStateEvent extends Event { + event: ProjectLanguageServiceStateEventName; + body?: ProjectLanguageServiceStateEventBody; + } + interface ProjectLanguageServiceStateEventBody { + /** + * Project name that has changes in the state of language service. + * For configured projects this will be the config file path. + * For external projects this will be the name of the projects specified when project was open. + * For inferred projects this event is not raised. + */ + projectName: string; + /** + * True if language service state switched from disabled to enabled + * and false otherwise. + */ + languageServiceEnabled: boolean; + } + type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; + interface ProjectsUpdatedInBackgroundEvent extends Event { + event: ProjectsUpdatedInBackgroundEventName; + body: ProjectsUpdatedInBackgroundEventBody; + } + interface ProjectsUpdatedInBackgroundEventBody { + /** + * Current set of open files + */ + openFiles: string[]; + } + /** + * Arguments for reload request. + */ + interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; + } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ReloadResponse extends Response { + } + /** + * Arguments for saveto request. + */ + interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; + } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + /** + * Arguments for navto request message. + */ + interface NavtoRequestArgs extends FileRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ + currentFileOnly?: boolean; + projectFileName?: string; + } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + /** + * An item found in a navto response. + */ + interface NavtoItem { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * exact, substring, or prefix. + */ + matchKind?: string; + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive?: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The file in which the symbol is found. + */ + file: string; + /** + * The location within file at which the symbol is found. + */ + start: Location; + /** + * One past the last character of the symbol. + */ + end: Location; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: ScriptElementKind; + } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + /** + * Arguments for change request message. + */ + interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; + } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + /** + * Response to "brace" request. + */ + interface BraceResponse extends Response { + body?: TextSpan[]; + } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + /** + * The item's display text. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ + indent: number; + } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ + interface NavigationTree { + text: string; + kind: ScriptElementKind; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } + type TelemetryEventName = "telemetry"; + interface TelemetryEvent extends Event { + event: TelemetryEventName; + body: TelemetryEventBody; + } + interface TelemetryEventBody { + telemetryEventName: string; + payload: any; + } + type TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; + interface TypesInstallerInitializationFailedEvent extends Event { + event: TypesInstallerInitializationFailedEventName; + body: TypesInstallerInitializationFailedEventBody; + } + interface TypesInstallerInitializationFailedEventBody { + message: string; + } + type TypingsInstalledTelemetryEventName = "typingsInstalled"; + interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { + telemetryEventName: TypingsInstalledTelemetryEventName; + payload: TypingsInstalledTelemetryEventPayload; + } + interface TypingsInstalledTelemetryEventPayload { + /** + * Comma separated list of installed typing packages + */ + installedPackages: string; + /** + * true if install request succeeded, otherwise - false + */ + installSuccess: boolean; + /** + * version of typings installer + */ + typingsInstallerVersion: string; + } + type BeginInstallTypesEventName = "beginInstallTypes"; + type EndInstallTypesEventName = "endInstallTypes"; + interface BeginInstallTypesEvent extends Event { + event: BeginInstallTypesEventName; + body: BeginInstallTypesEventBody; + } + interface EndInstallTypesEvent extends Event { + event: EndInstallTypesEventName; + body: EndInstallTypesEventBody; + } + interface InstallTypesEventBody { + /** + * correlation id to match begin and end events + */ + eventId: number; + /** + * list of packages to install + */ + packages: ReadonlyArray; + } + interface BeginInstallTypesEventBody extends InstallTypesEventBody { + } + interface EndInstallTypesEventBody extends InstallTypesEventBody { + /** + * true if installation succeeded, otherwise false + */ + success: boolean; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } + const enum IndentStyle { + None = "None", + Block = "Block", + Smart = "Smart" + } + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterConstructor?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + insertSpaceBeforeFunctionParenthesis?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ + readonly includeCompletionsForModuleExports?: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly allowTextChangesInNewFiles?: boolean; + } + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + checkJs?: boolean; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + downlevelIteration?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + plugins?: PluginImport[]; + preserveConstEnums?: boolean; + preserveSymlinks?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + references?: ProjectReference[]; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strict?: boolean; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + resolveJsonModule?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + const enum JsxEmit { + None = "None", + Preserve = "Preserve", + ReactNative = "ReactNative", + React = "React" + } + const enum ModuleKind { + None = "None", + CommonJS = "CommonJS", + AMD = "AMD", + UMD = "UMD", + System = "System", + ES6 = "ES6", + ES2015 = "ES2015", + ESNext = "ESNext" + } + const enum ModuleResolutionKind { + Classic = "Classic", + Node = "Node" + } + const enum NewLineKind { + Crlf = "Crlf", + Lf = "Lf" + } + const enum ScriptTarget { + ES3 = "ES3", + ES5 = "ES5", + ES6 = "ES6", + ES2015 = "ES2015", + ES2016 = "ES2016", + ES2017 = "ES2017", + ESNext = "ESNext" + } +} +declare namespace ts.server.protocol { + + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + + interface TodoCommentDescriptor { + text: string; + priority: number; + } + + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + + enum OutliningSpanKind { + /** Single or multi-line comments */ + Comment = "comment", + /** Sections marked by '// #region' and '// #endregion' comments */ + Region = "region", + /** Declarations and expressions */ + Code = "code", + /** Contiguous blocks of import declarations */ + Imports = "imports" + } + + enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference" + } + + enum ScriptElementKind { + unknown = "", + warning = "warning", + /** predefined type (void) or keyword (class) */ + keyword = "keyword", + /** top level script node */ + scriptElement = "script", + /** module foo {} */ + moduleElement = "module", + /** class X {} */ + classElement = "class", + /** var x = class X {} */ + localClassElement = "local class", + /** interface Y {} */ + interfaceElement = "interface", + /** type T = ... */ + typeElement = "type", + /** enum E */ + enumElement = "enum", + enumMemberElement = "enum member", + /** + * Inside module and script only + * const v = .. + */ + variableElement = "var", + /** Inside function */ + localVariableElement = "local var", + /** + * Inside module and script only + * function f() { } + */ + functionElement = "function", + /** Inside function */ + localFunctionElement = "local function", + /** class X { [public|private]* foo() {} } */ + memberFunctionElement = "method", + /** class X { [public|private]* [get|set] foo:number; } */ + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + memberVariableElement = "property", + /** class X { constructor() { } } */ + constructorImplementationElement = "constructor", + /** interface Y { ():number; } */ + callSignatureElement = "call", + /** interface Y { []:number; } */ + indexSignatureElement = "index", + /** interface Y { new():Y; } */ + constructSignatureElement = "construct", + /** function foo(*Y*: string) */ + parameterElement = "parameter", + typeParameterElement = "type parameter", + primitiveType = "primitive type", + label = "label", + alias = "alias", + constElement = "const", + letElement = "let", + directory = "directory", + externalModuleName = "external module name", + /** + * + */ + jsxAttribute = "JSX attribute", + /** String literal */ + string = "string" + } + + interface TypeAcquisition { + enableAutoDiscovery?: boolean; + enable?: boolean; + include?: string[]; + exclude?: string[]; + [option: string]: string[] | boolean | undefined; + } + + interface FileExtensionInfo { + extension: string; + isMixedContent: boolean; + scriptKind?: ScriptKind; + } + + interface JSDocTagInfo { + name: string; + text?: string; + } + + /** + * Type of objects whose values are all of the same type. + * The `in` and `for-in` operators can *not* be safely used, + * since `Object.prototype` may be modified by outside code. + */ + interface MapLike { + [index: string]: T; + } + + interface PluginImport { + name: string; + } + + interface ProjectReference { + /** A normalized path on disk */ + path: string; + /** The path as the user originally wrote it */ + originalPath?: string; + /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ + prepend?: boolean; + /** True if it is intended that this reference form a circularity */ + circular?: boolean; + } + + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; +} +declare namespace ts { + // these types are empty stubs for types from services and should not be used directly + export type ScriptKind = never; + export type IndentStyle = never; + export type JsxEmit = never; + export type ModuleKind = never; + export type ModuleResolutionKind = never; + export type NewLineKind = never; + export type ScriptTarget = never; +} +import protocol = ts.server.protocol; +export = protocol; +export as namespace protocol; \ No newline at end of file diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index 1a80b918eab..fd953b416a9 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "Adicionar inicializador à propriedade '{0}'", "Add_initializers_to_all_uninitialized_properties_95027": "Adicionar inicializadores a todas as propriedades não inicializadas", "Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente", + "Add_missing_typeof_95052": "Adicionar typeof ausente", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Adicionar um qualificador a todas as variáveis não resolvidas correspondentes a um nome de membro", "Add_to_all_uncalled_decorators_95044": "Adicionar '()' a todos os decoradores não chamados", "Add_ts_ignore_to_all_error_messages_95042": "Adicionar '@ts-ignore' a todas as mensagens de erro", @@ -117,6 +118,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas as declarações de '{0}' devem ter modificadores idênticos.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas as declarações de '{0}' devem ter parâmetros de tipo idênticos.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas as declarações de um método abstrato devem ser consecutivas.", + "All_destructured_elements_are_unused_6198": "Todos os elementos desestruturados são inutilizados.", "All_imports_in_import_declaration_are_unused_6192": "Nenhuma das importações na declaração de importação está sendo utilizada.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permita importações padrão de módulos sem exportação padrão. Isso não afeta a emissão do código, apenas a verificação de digitação.", "Allow_javascript_files_to_be_compiled_6102": "Permita que arquivos javascript sejam compilados.", @@ -220,6 +222,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Não é possível invocar um objeto que é possivelmente 'nulo'.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Não é possível invocar um objeto que é possivelmente 'nulo' ou 'indefinido'.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Não é possível invocar um objeto que é possivelmente 'indefinido'.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Não é possível preceder o projeto '{0}' porque ele não tem o conjunto 'outFile'", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Não será possível reexportar um tipo quando o sinalizador '--isolatedModules' for fornecido.", "Cannot_read_file_0_Colon_1_5012": "Não é possível ler o arquivo '{0}': {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Não é possível declarar novamente a variável de escopo de bloco '{0}'.", @@ -260,6 +263,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compile o projeto dando o caminho para seu arquivo de configuração ou para uma pasta com um 'tsconfig.json'.", "Compiler_option_0_expects_an_argument_6044": "A opção do compilador '{0}' espera um argumento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "A opção do compilador '{0}' requer um valor do tipo {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Projetos compostos não podem desabilitar a emissão de declaração.", "Computed_property_names_are_not_allowed_in_enums_1164": "Nomes de propriedade calculados não são permitidos em enums.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Os valores computados não são permitidos em uma enumeração com membros de valor de cadeia de caracteres.", "Concatenate_and_emit_output_to_single_file_6001": "Concatenar e emitir saída para um arquivo único.", @@ -271,9 +275,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Construtores para classes derivadas devem conter uma chamada 'super'.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "O arquivo contido não foi especificado e o diretório raiz não pode ser determinado, ignorando a pesquisa na pasta 'node_modules'.", "Convert_all_constructor_functions_to_classes_95045": "Converter todas as funções de construtor em classes", + "Convert_all_require_to_import_95048": "Converter todos os 'require' em 'import'", "Convert_all_to_default_imports_95035": "Converter tudo para importações padrão", "Convert_function_0_to_class_95002": "Converter função '{0}' em classe", "Convert_function_to_an_ES2015_class_95001": "Converter função em uma classe ES2015", + "Convert_require_to_import_95047": "Converter 'require' em 'import'", "Convert_to_ES6_module_95017": "Converter em módulo ES6", "Convert_to_default_import_95013": "Converter para importação padrão", "Corrupted_locale_file_0_6051": "Arquivo de localidade {0} corrompido.", @@ -326,8 +332,8 @@ "Duplicate_label_0_1114": "Rótulo '{0}' duplicado.", "Duplicate_number_index_signature_2375": "Assinatura de índice de número duplicado.", "Duplicate_string_index_signature_2374": "Assinatura de índice de cadeia de caracteres duplicada.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "A importação dinâmica não pode ser usada ao destinar módulos de ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "A importação dinâmica não pode ter argumentos de tipo", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Só há suporte para importação dinâmica quando o sinalizador '--module' é 'commonjs' ou 'esNext'.", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "A importação dinâmica deve ter um especificador como um argumento.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "O especificador da importação dinâmica deve ser do tipo 'string', mas aqui tem o tipo '{0}'.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "O elemento implicitamente tem um tipo 'any' porque a expressão de índice não é do tipo 'number'.", @@ -336,6 +342,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir um arquivo único com os mapas de origem em vez de arquivos separados.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir a origem ao lado dos sourcemaps em um arquivo único; a definição requer '--inlineSourceMap' ou '--sourceMap'.", "Enable_all_strict_type_checking_options_6180": "Habilitar todas as opções estritas de verificação de tipo.", + "Enable_project_compilation_6302": "Habilitar a compilação do projeto", "Enable_strict_checking_of_function_types_6186": "Habilitar verificação estrita de tipos de função.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite a verificação estrita de inicialização de propriedade nas classes.", "Enable_strict_null_checks_6113": "Habilite verificações nulas estritas.", @@ -397,6 +404,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "O arquivo '{0}' tem uma extensão sem suporte, portanto ele será ignorado.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "O arquivo '{0}' tem extensão sem suporte. As únicas extensões com suporte são {1}.", "File_0_is_not_a_module_2306": "O arquivo '{0}' não é um módulo.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "O arquivo '{0}' não está na lista de arquivos de projeto. Os projetos devem listar todos os arquivos ou usar um padrão 'include'.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "O arquivo '{0}' não está em 'rootDir' '{1}'. Espera-se que 'rootDir' contenha todos os arquivos de origem.", "File_0_not_found_6053": "Arquivo '{0}' não encontrado.", "File_change_detected_Starting_incremental_compilation_6032": "Alteração do arquivo detectada. Iniciando compilação incremental...", @@ -461,6 +469,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Em declarações de enumeração de ambiente, o inicializador de membro deve ser uma expressão de constante.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Em uma enumeração com várias declarações, somente uma declaração pode omitir um inicializador para o primeiro elemento de enumeração.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Em declarações de enumeração 'const', o inicializador de membro deve ser uma expressão de constante.", + "Include_modules_imported_with_json_extension_6197": "Incluir módulos importados com a extensão '.json'", "Index_signature_in_type_0_only_permits_reading_2542": "Assinatura de índice no tipo '{0}' permite somente leitura.", "Index_signature_is_missing_in_type_0_2329": "Assinatura de índice ausente no tipo '{0}'.", "Index_signatures_are_incompatible_2330": "As assinaturas de índice são incompatíveis.", @@ -559,6 +568,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Nome do módulo '{0}' foi resolvido com sucesso '{1}'. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Resolução de tipo não foi especificado, usando '{0}'.", "Module_resolution_using_rootDirs_has_failed_6111": "Falha na resolução de módulo usando 'rootDirs'.", + "Move_to_a_new_file_95049": "Mover para um novo arquivo", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Não são permitidos vários separadores numéricos consecutivos.", "Multiple_constructor_implementations_are_not_allowed_2392": "Não são permitidas várias implementações de construtor.", "NEWLINE_6061": "NEWLINE", @@ -600,8 +610,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "A opção 'isolatedModules' só pode ser usada quando nenhuma opção de '--module' for fornecida ou a opção 'target' for 'ES2015' ou superior.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "A opção 'paths' não pode ser usada sem se especificar a opção '--baseUrl'.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "A opção 'project' não pode ser mesclada com arquivos de origem em uma linha de comando.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "A opção '--resolveJsonModule' não pode ser especificada sem a estratégia de resolução de módulo de 'nó'.", "Options_Colon_6027": "Opções:", "Output_directory_for_generated_declaration_files_6166": "Diretório de saída para os arquivos de declaração gerados.", + "Output_file_0_from_project_1_does_not_exist_6309": "O arquivo de saída '{0}' do projeto '{1}' não existe", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "O arquivo de saída '{0}' não foi compilado do arquivo de origem '{1}'.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "A assinatura de sobrecarga não é compatível com a implementação da função.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Assinaturas de sobrecarga devem todas ser abstratas ou não abstratas.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Todas as assinaturas de sobrecarga devem ser ambiente ou não ambiente.", @@ -645,6 +658,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Nomes de impressão das partes dos arquivos gerados da compilação.", "Print_the_compiler_s_version_6019": "Imprima a versão do compilador.", "Print_this_message_6017": "Imprima esta mensagem.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Referências de projeto não podem formar um gráfico circular. Ciclo detectado: {0}", + "Projects_to_reference_6300": "Projetos para referência", "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe na enumeração 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "A propriedade '{0}' não existe no tipo '{1}'. Você esqueceu de usar 'await'?", @@ -692,8 +707,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Gerar erro em expressões e declarações com um tipo 'any' implícito.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Gerar erro em expressões 'this' com um tipo 'any' implícito.", "Redirect_output_structure_to_the_directory_6006": "Redirecione a estrutura de saída para o diretório.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "O projeto referenciado '{0}' deve ter a configuração de \"composite\": true.", + "Remove_all_unreachable_code_95051": "Remover todo o código inacessível", "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", + "Remove_destructuring_90009": "Remover desestruturação", "Remove_import_from_0_90005": "Remover importação do '{0}'", + "Remove_unreachable_code_95050": "Remover código inacessível", "Replace_import_with_0_95015": "Substitua a importação com '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Relate erro quando nem todos os caminhos de código na função retornarem um valor.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Relate erros para casos de fallthrough na instrução switch.", @@ -801,7 +820,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "A lista de 'arquivos' no arquivo de configuração '{0}' está vazia.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "O primeiro parâmetro do método 'then' de uma promessa deve ser um retorno de chamada.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "O tipo global 'JSX.{0}' não pode ter mais de uma propriedade.", - "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "A metapropriedade 'import.meta' é permitida apenas usando 'ESNext' para as opções de compilador 'target' e 'module'.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "O tipo inferido de '{0}' faz referência a um tipo '{1}' inacessível. Uma anotação de tipo é necessária.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "O lado esquerdo de uma instrução 'for...in' não pode ser um padrão de desestruturação.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "O lado esquerdo de uma instrução 'for...in' não pode usar uma anotação de tipo.", @@ -1014,6 +1033,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' só podem ser usados em um arquivo .ts.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "A opção 'paths' é especificada, procurando por um padrão para corresponder ao nome do módulo '{0}'.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "O modificador 'readonly' pode aparecer somente em uma declaração de propriedade ou assinatura de índice.", + "require_call_may_be_converted_to_an_import_80005": "A chamada 'require' pode ser convertida em uma importação.", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "A opção 'rootDirs' está configurada, usando-a para resolver o nome de módulo relativo '{0}'.", "super_can_only_be_referenced_in_a_derived_class_2335": "'super' só pode ser referenciado em uma classe derivada.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' pode ser referido somente em membros de classes derivadas ou expressões literais de objeto.", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index 0c3939a3916..dc4efb499e5 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Все объявления \"{0}\" должны иметь одинаковые модификаторы.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Все объявления \"{0}\" должны иметь одинаковые параметры типа.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Все объявления абстрактных методов должны быть последовательными.", + "All_destructured_elements_are_unused_6198": "Все деструктурированные элементы не используются.", "All_imports_in_import_declaration_are_unused_6192": "Ни один из импортов в объявлении импорта не используется.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Разрешить импорт по умолчанию из модулей без экспорта по умолчанию. Это не повлияет на выведение кода — только на проверку типов.", "Allow_javascript_files_to_be_compiled_6102": "Разрешить компиляцию файлов javascript.", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Не удается вызвать объект, который может иметь значение \"NULL\".", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Не удается вызвать объект, который может иметь значение \"NULL\" или \"undefined\".", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Не удается вызвать объект, который может иметь значение \"undefined\".", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Невозможно добавить проект \"{0}\" в начало, так как для него не задан outFile", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Невозможно повторно экспортировать тип, если установлен флажок \"--isolatedModules\".", "Cannot_read_file_0_Colon_1_5012": "Не удается считать файл \"{0}\": {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Невозможно повторно объявить переменную \"{0}\" с областью видимости \"Блок\".", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Компиляция проекта по заданному пути к файлу конфигурации или папке с файлом tsconfig.json.", "Compiler_option_0_expects_an_argument_6044": "Параметр компилятора \"{0}\" ожидает аргумент.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Параметр \"{0}\" компилятора требует значение типа {1}.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Составные проекты не могут отключать выпуск объявления.", "Computed_property_names_are_not_allowed_in_enums_1164": "Имена вычисляемых свойств запрещены в перечислениях.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Вычисленные значения запрещены в перечислении с членами, имеющими строковые значения.", "Concatenate_and_emit_output_to_single_file_6001": "Связать и вывести результаты в один файл.", @@ -271,9 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Конструкторы производных классов должны содержать вызов super.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Содержащий файл не указан, корневой каталог невозможно определить. Выполняется пропуск поиска в папке node_modules.", "Convert_all_constructor_functions_to_classes_95045": "Преобразовать все функции конструктора в классы", + "Convert_all_require_to_import_95048": "Преобразовать все \"require\" в \"import\"", "Convert_all_to_default_imports_95035": "Преобразовать все в импорт по умолчанию", "Convert_function_0_to_class_95002": "Преобразование функции \"{0}\" в класс", "Convert_function_to_an_ES2015_class_95001": "Преобразование функции в класс ES2015", + "Convert_require_to_import_95047": "Преобразовать \"require\" в \"import\"", "Convert_to_ES6_module_95017": "Преобразовать в модуль ES6", "Convert_to_default_import_95013": "Преобразовать в импорт по умолчанию", "Corrupted_locale_file_0_6051": "Поврежденный файл языкового стандарта \"{0}\".", @@ -326,8 +331,8 @@ "Duplicate_label_0_1114": "Повторяющаяся метка \"{0}\".", "Duplicate_number_index_signature_2375": "Повторяющаяся сигнатура числового индекса.", "Duplicate_string_index_signature_2374": "Повторяющаяся сигнатура строкового индекса.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Динамический импорт не может использоваться с модулями ECMAScript 2015.", "Dynamic_import_cannot_have_type_arguments_1326": "При динамическом импорте не могут использоваться аргументы типов", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Динамический импорт поддерживается, только если флаг \"--module\" имеет значение \"commonjs\" или \"esNext\".", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "При динамическом импорте необходимо указать один описатель в качестве аргумента.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Описатель динамического импорта должен иметь тип \"string\", но имеет тип \"{0}\".", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Элемент неявно содержит тип any, так как выражение индекса не имеет тип number.", @@ -336,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Порождать один файл с сопоставлениями источников, а не создавать отдельный файл.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Порождать источник вместе с sourcemap в одном файле (нужно задать параметр --inlineSourceMap или --sourceMap).", "Enable_all_strict_type_checking_options_6180": "Включить все параметры строгой проверки типов.", + "Enable_project_compilation_6302": "Включить компиляцию проекта", "Enable_strict_checking_of_function_types_6186": "Включение строгой проверки типов функций.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Включение строгой проверки инициализации свойств в классах.", "Enable_strict_null_checks_6113": "Включить строгие проверки NULL.", @@ -397,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Файл \"{0}\" имеет неподдерживаемое разрешение, поэтому будет пропущен.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Файл \"{0}\" имеет неподдерживаемое расширение. Поддерживаются только следующие расширения: {1}.", "File_0_is_not_a_module_2306": "Файл \"{0}\" не является модулем.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Файл \"{0}\" отсутствует в списке файлов проекта. Проекты должны перечислять все файлы или использовать шаблон включения.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Файл \"{0}\" отсутствует в \"rootDir\" \"{1}\". Все исходные файлы должны находиться в каталоге \"rootDir\".", "File_0_not_found_6053": "Файл \"{0}\" не найден.", "File_change_detected_Starting_incremental_compilation_6032": "Обнаружено изменение в файле. Запускается инкрементная компиляция...", @@ -461,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Во внешних объявлениях перечислений инициализатор элемента должен быть константным выражением.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "В перечислении с несколькими объявлениями только одно объявление может опустить инициализатор для своего первого элемента перечисления.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "В инициализаторе элементов объявлений перечисления const должно быть константным выражением.", + "Include_modules_imported_with_json_extension_6197": "Включать модули, импортированные с расширением .json", "Index_signature_in_type_0_only_permits_reading_2542": "Сигнатура индекса в типе \"{0}\" разрешает только чтение.", "Index_signature_is_missing_in_type_0_2329": "В типе \"{0}\" отсутствует сигнатура индекса.", "Index_signatures_are_incompatible_2330": "Сигнатуры индекса несовместимы.", @@ -559,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Имя модуля \"{0}\" было успешно разрешено в \"{1}\". ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Тип разрешения модуля не указан, используется \"{0}\".", "Module_resolution_using_rootDirs_has_failed_6111": "Произошел сбой при разрешении модуля с помощью \"rootDirs\".", + "Move_to_a_new_file_95049": "Переместить в новый файл", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Использовать несколько последовательных числовых разделителей запрещено.", "Multiple_constructor_implementations_are_not_allowed_2392": "Не разрешается использование нескольких реализаций конструкторов.", "NEWLINE_6061": "НОВАЯ СТРОКА", @@ -600,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Параметр isolatedModules можно использовать, только если указан параметр --module или если параметр target — ES2015 или выше.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Параметр paths невозможно использовать без указания параметра \"--baseUrl\".", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Параметр project не может быть указан вместе с исходными файлами в командной строке.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Параметр \"--resolveJsonModule\" нельзя указать без стратегии разрешения модуля node.", "Options_Colon_6027": "Параметры:", "Output_directory_for_generated_declaration_files_6166": "Выходной каталог для создаваемых файлов объявления.", + "Output_file_0_from_project_1_does_not_exist_6309": "Выходной файл \"{0}\" из проекта \"{1}\" не существует", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Выходной файл \"{0}\" не создан из исходного файла \"{1}\".", "Overload_signature_is_not_compatible_with_function_implementation_2394": "Сигнатура перегрузки несовместима с реализацией функции.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Сигнатуры перегрузки должны быть абстрактными или неабстрактными.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Все сигнатуры перегрузки должны быть либо внешними, либо не внешними.", @@ -645,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Печатать имена создаваемых файлов, входящих в компиляцию.", "Print_the_compiler_s_version_6019": "Печать версии компилятора.", "Print_this_message_6017": "Напечатайте это сообщение.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Ссылки на проект не могут формировать циклический граф. Обнаружен цикл: {0}", + "Projects_to_reference_6300": "Проекты для ссылки", "Property_0_does_not_exist_on_const_enum_1_2479": "Свойство \"{0}\" не существует в перечислении const \"{1}\".", "Property_0_does_not_exist_on_type_1_2339": "Свойство \"{0}\" не существует в типе \"{1}\".", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Свойство \"{0}\" не существует в типе \"{1}\". Возможно, пропущено \"await\"?", @@ -692,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Вызывать ошибку в выражениях и объявлениях с подразумеваемым типом any.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Вызвать ошибку в выражениях this с неявным типом any.", "Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Указанный в ссылке проект \"{0}\" должен иметь следующее значение параметра composite: true.", + "Remove_all_unreachable_code_95051": "Удалить весь недостижимый код", "Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\"", + "Remove_destructuring_90009": "Удалить деструктурирование", "Remove_import_from_0_90005": "Удалить импорт из \"{0}\"", + "Remove_unreachable_code_95050": "Удалить недостижимый код", "Replace_import_with_0_95015": "Замена импорта на \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.", @@ -801,6 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "Список \"files\" в файле конфигурации \"{0}\" пуст.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Первым параметром метода then класса promise должен быть обратный вызов.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Метасвойство \"import.meta\" разрешено только при использовании \"ESNext\" для параметров компилятора \"target\" и \"module\".", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Выведенный тип \"{0}\" ссылается на недоступный тип \"{1}\". Требуется аннотация типа.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Левый операнд оператора for...in не может быть шаблоном деструктурирования.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Левый операнд оператора for...in не может использовать аннотацию типа.", @@ -1013,6 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Модификаторы параметров могут использоваться только в TS-файле.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Параметр paths указан, идет поиск шаблона, соответствующего имени модуля \"{0}\".", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Модификатор readonly может отображаться только в объявлении свойства или сигнатуре индекса.", + "require_call_may_be_converted_to_an_import_80005": "Вызов \"require\" можно преобразовать в \"import\".", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Параметр \"rootDirs\" задан; он используется для разрешения относительного имени модуля \"{0}\".", "super_can_only_be_referenced_in_a_derived_class_2335": "Ссылка на super может указываться только в производном классе.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "На super можно ссылаться только в элементах производных классов или литеральных выражениях объекта.", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 8c998ffd6cc..d037f7d0d20 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Tüm '{0}' bildirimleri aynı değiştiricilere sahip olmalıdır.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tüm '{0}' bildirimleri özdeş tür parametrelerine sahip olmalıdır.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.", + "All_destructured_elements_are_unused_6198": "Yok edilen öğelerin hiçbiri kullanılmamış.", "All_imports_in_import_declaration_are_unused_6192": "İçeri aktarma bildirimindeki hiçbir içeri aktarma kullanılmadı.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", "Allow_javascript_files_to_be_compiled_6102": "Javascript dosyalarının derlenmesine izin ver.", @@ -133,6 +134,7 @@ "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Zaman uyumsuz bir işlev veya metot, geçerli bir beklenebilir dönüş türüne sahip olmalıdır.", "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Zaman uyumsuz bir işlevin veya metodun 'Promise' döndürmesi gerekir. Bir 'Promise' bildiriminiz olduğundan emin olun veya `--lib` seçeneğinize 'ES2015' ifadesini ekleyin.", "An_async_iterator_must_have_a_next_method_2519": "Zaman uyumsuz yineleyicinin bir 'next()' metodu olmalıdır.", + "An_element_access_expression_should_take_an_argument_1011": "Bir öğe erişimi ifadesi bir bağımsız değişken almalıdır.", "An_enum_member_cannot_have_a_numeric_name_2452": "Sabit listesi üyesi, sayısal bir ada sahip olamaz.", "An_export_assignment_can_only_be_used_in_a_module_1231": "Dışarı aktarma ataması yalnızca bir modülde kullanılabilir.", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Dışarı aktarma ataması, dışarı aktarılmış diğer öğelere sahip bir modülde kullanılamaz.", @@ -219,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Muhtemelen 'null' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Muhtemelen 'null' veya 'undefined' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Muhtemelen 'undefined' olan bir nesne çağrılamıyor.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' projesi, 'outFile' kümesi içermediğinden başa eklenemiyor", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' bayrağı sağlandığında bir tür yeniden dışarı aktarılamaz.", "Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.", @@ -259,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Yapılandırma dosyasının yolu veya 'tsconfig.json' dosyasını içeren klasörün yolu belirtilen projeyi derleyin.", "Compiler_option_0_expects_an_argument_6044": "'{0}' derleyici seçeneği, bağımsız değişken bekliyor.", "Compiler_option_0_requires_a_value_of_type_1_5024": "'{0}' derleyici seçeneği, {1} türünde bir değer gerektiriyor.", + "Composite_projects_may_not_disable_declaration_emit_6304": "Bileşik projeler, bildirim gösterimini devre dışı bırakamaz.", "Computed_property_names_are_not_allowed_in_enums_1164": "Sabit listelerinde hesaplanan özellik adına izin verilmiyor.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Dize değeri içeren üyelerin bulunduğu bir sabit listesinde hesaplanan değerlere izin verilmez.", "Concatenate_and_emit_output_to_single_file_6001": "Çıktıyı tek dosyaya birleştirin ve yayın.", @@ -270,9 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Türetilmiş sınıflara ilişkin oluşturucular bir 'super' çağrısı içermelidir.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Kapsayıcı dosya belirtilmedi ve kök dizini belirlenemiyor; 'node_modules' klasöründe arama atlanıyor.", "Convert_all_constructor_functions_to_classes_95045": "Tüm oluşturucu işlevleri sınıflara dönüştür", + "Convert_all_require_to_import_95048": "Tüm 'require' öğelerini 'import' olarak dönüştür", "Convert_all_to_default_imports_95035": "Tümünü varsayılan içeri aktarmalara dönüştür", "Convert_function_0_to_class_95002": "'{0}' işlevini sınıfa dönüştür", "Convert_function_to_an_ES2015_class_95001": "İşlevi bir ES2015 sınıfına dönüştür", + "Convert_require_to_import_95047": "'require' öğesini 'import' olarak dönüştür", "Convert_to_ES6_module_95017": "ES6 modülüne dönüştür", "Convert_to_default_import_95013": "Varsayılan içeri aktarmaya dönüştür", "Corrupted_locale_file_0_6051": "{0} yerel ayar dosyası bozuk.", @@ -325,8 +331,8 @@ "Duplicate_label_0_1114": "'{0}' etiketi yineleniyor.", "Duplicate_number_index_signature_2375": "Dizin imzasında yinelenen numara.", "Duplicate_string_index_signature_2374": "Dizin imzasında yinelenen dize.", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 modülleri hedeflenirken dinamik içeri aktarma kullanılamaz.", "Dynamic_import_cannot_have_type_arguments_1326": "Dinamik içeri aktarma, tür bağımsız değişkenleri içeremez", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Dinamik içeri aktarma yalnızca '--module' bayrağı 'commonjs' veya 'esNext' olduğunda desteklenir.", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dinamik içeri aktarma, bağımsız değişken olarak bir tanımlayıcı içermelidir.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Dinamik içeri aktarmanın tanımlayıcısı 'string' türünde olmalıdır, ancak buradaki tür: '{0}'.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Dizin ifadesi 'number' türünde olmadığından, öğe örtük olarak 'any' türü içeriyor.", @@ -335,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Ayrı bir dosya oluşturmak yerine, kaynak eşlemeleri içeren tek bir dosya gösterin.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Kaynağı, kaynak eşlemeleri ile birlikte tek bir dosya içinde gösterin; '--inlineSourceMap' veya '--sourceMap' öğesinin ayarlanmasını gerektirir.", "Enable_all_strict_type_checking_options_6180": "Tüm katı tür denetleme seçeneklerini etkinleştirin.", + "Enable_project_compilation_6302": "Proje derlemeyi etkinleştir", "Enable_strict_checking_of_function_types_6186": "İşlev türleri üzerinde katı denetimi etkinleştirin.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Sınıflarda sıkı özellik başlatma denetimini etkinleştirin.", "Enable_strict_null_checks_6113": "Katı null denetimlerini etkinleştir.", @@ -396,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "'{0}' dosyasının desteklenmeyen bir uzantısı olduğundan dosya atlanıyor.", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' dosyası desteklenmeyen uzantıya sahip. Yalnızca {1} uzantıları desteklenir.", "File_0_is_not_a_module_2306": "'{0}' dosyası bir modül değil.", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "'{0}' dosyası, proje dosyası listesinde değil. Projelerin tüm dosyaları listelemesi veya bir 'include' düzeni kullanması gerekir.", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' dosyası, 'rootDir' '{1}' dizininde değil. 'rootDir' dizininin tüm kaynak dosyalarını içermesi bekleniyor.", "File_0_not_found_6053": "'{0}' dosyası bulunamadı.", "File_change_detected_Starting_incremental_compilation_6032": "Dosya değişikliği algılandı. Artımlı derleme başlatılıyor...", @@ -460,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Çevresel sabit listesi bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Birden fazla bildirime sahip sabit listesinde yalnızca bir bildirim ilk sabit listesi öğesine ait başlatıcıyı atlayabilir.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' sabit listesi bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", + "Include_modules_imported_with_json_extension_6197": "'.json' uzantısıyla içeri aktarılan modülleri dahil et", "Index_signature_in_type_0_only_permits_reading_2542": "'{0}' türündeki dizin imzası yalnızca okumaya izin veriyor.", "Index_signature_is_missing_in_type_0_2329": "'{0}' türündeki dizin imzası yok.", "Index_signatures_are_incompatible_2330": "Dizin imzaları uyumsuz.", @@ -558,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== '{0}' modül adı '{1}' öğesine başarıyla çözümlendi. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Modül çözümleme türü belirtilmedi, '{0}' kullanılıyor.", "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' kullanarak modül çözümleme başarısız oldu.", + "Move_to_a_new_file_95049": "Yeni bir dosyaya taşı", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Birbirini izleyen birden çok sayısal ayırıcıya izin verilmez.", "Multiple_constructor_implementations_are_not_allowed_2392": "Birden çok oluşturucu uygulamasına izin verilmez.", "NEWLINE_6061": "YENİ SATIR", @@ -599,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' seçeneği, yalnızca '--module' sağlandığında veya 'target' seçeneği 'ES2015' veya daha yüksek bir sürüm değerine sahip olduğunda kullanılabilir.", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "'Paths' seçeneği, '--baseUrl' seçeneği belirtilmeden kullanılamaz.", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "'project' seçeneği, komut satırındaki kaynak dosyalarıyla karıştırılamaz.", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' modül çözümleme stratejisi olmadan '--resolveJsonModule' seçeneği belirtilemez.", "Options_Colon_6027": "Seçenekler:", "Output_directory_for_generated_declaration_files_6166": "Oluşturulan bildirim dosyaları için çıkış dizini.", + "Output_file_0_from_project_1_does_not_exist_6309": "'{1}' projesinden '{0}' çıkış dosyası yok", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Çıkış dosyası '{0}' '{1}' kaynak dosyasından oluşturulmamış.", "Overload_signature_is_not_compatible_with_function_implementation_2394": "Aşırı yükleme imzası işlev uygulamasıyla uyumlu değil.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Aşırı yükleme imzalarının hepsi soyut veya soyut olmayan olmalıdır.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Aşırı yükleme imzalarının tümü çevresel veya çevresel olmayan türde olmalıdır.", @@ -644,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "Oluşturulan dosyalardan, derlemenin parçası olanların adlarını yazdırın.", "Print_the_compiler_s_version_6019": "Derleyici sürümünü yazdır.", "Print_this_message_6017": "Bu iletiyi yazdır.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Proje başvuruları döngüsel bir grafik formu oluşturamaz. Döngü tespit edildi: {0}", + "Projects_to_reference_6300": "Başvurulacak projeler", "Property_0_does_not_exist_on_const_enum_1_2479": "'{0}' özelliği, '{1}' 'const' sabit listesi üzerinde değil.", "Property_0_does_not_exist_on_type_1_2339": "'{0}' özelliği, '{1}' türünde değil.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "'{0}' özelliği '{1}' türü üzerinde yok. 'await' kullanmayı mı unuttunuz?", @@ -691,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Belirtilen 'any' türüne sahip ifade ve bildirimlerde hata oluştur.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Örtük olarak 'any' türü içeren 'this' ifadelerinde hata tetikle.", "Redirect_output_structure_to_the_directory_6006": "Çıktı yapısını dizine yeniden yönlendir.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Başvurulan proje '{0}' \"composite\": true ayarına sahip olmalıdır.", + "Remove_all_unreachable_code_95051": "Tüm erişilemeyen kodları kaldır", "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır", + "Remove_destructuring_90009": "Yıkmayı kaldır", "Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır", + "Remove_unreachable_code_95050": "Erişilemeyen kodları kaldır", "Replace_import_with_0_95015": "İçeri aktarma işlemini '{0}' ile değiştirin.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "İşlevdeki tüm kod yolları bir değer döndürmediğinde hata bildir.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch deyiminde sonraki ifadelere geçiş ile ilgili hataları bildir.", @@ -701,7 +720,7 @@ "Report_errors_on_unused_parameters_6135": "Kullanılmayan parametrelerdeki hataları bildirin.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Gerekli tür parametreleri, isteğe bağlı tür parametrelerini takip edemez.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' modülünün çözümü '{1}' konumundaki önbellekte bulundu.", - "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolve 'keyof' to string valued property names only (no numbers or symbols).", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'Keyof' değerini yalnızca dize değerli özellik adlarına (sayılar veya simgeler olmadan) çözümleyin.", "Resolving_from_node_modules_folder_6118": "Node_modules klasöründen çözümleniyor...", "Resolving_module_0_from_1_6086": "======== '{0}' modülü '{1}' öğesinden çözümleniyor. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "'{0}' modül adı, '{1}' - '{2}' temel url'sine göre çözümleniyor.", @@ -800,6 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "'{0}' yapılandırma dosyasındaki 'dosyalar' listesi boş.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise'in 'then' metodunun ilk parametresi, bir geri arama parametresi olmalıdır.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "'JSX.{0}' genel türü birden fazla özelliğe sahip olamaz.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "'import.meta' meta özelliğine yalnızca 'target' ve 'module' derleyici seçenekleri için 'ESNext' kullanıldığında izin verilir.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Çıkarsanan '{0}' türü, erişilemeyen bir '{1}' türüne başvuruyor. Tür ek açıklaması gereklidir.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' deyiminin sol tarafı yok etme deseni olamaz.", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' deyiminin sol tarafında tür ek açıklaması kullanılamaz.", @@ -947,7 +967,7 @@ "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "Bir tür ek açıklamasına sahip olmadığından ve kendi başlatıcısında doğrudan veya dolaylı olarak başvurulduğundan, '{0}' öğesi örtük olarak 'any' türüne sahip.", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' temel elemandır ancak '{1}' sarmalayıcı nesnedir. Mümkün olduğunda '{0}' kullanmayı tercih edin.", "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' bildirildi ancak değeri hiç okunmadı.", - "_0_is_declared_but_never_used_6196": "'{0}' is declared but never used.", + "_0_is_declared_but_never_used_6196": "'{0}' bildirildi ancak hiç kullanılmadı.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}', '{1}' anahtar sözcüğü için geçerli bir meta özellik değil. Bunu mu demek istediniz: '{2}'?", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' öğesine kendi temel ifadesinde doğrudan veya dolaylı olarak başvuruluyor.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' öğesine kendi tür ek açıklamasında doğrudan veya dolaylı olarak başvuruluyor.", @@ -1012,6 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' yalnızca bir .ts dosyasında kullanılabilir.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' seçeneği belirtildi, '{0}' modül adıyla eşleşen bir desen aranıyor.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' değiştiricisi yalnızca özellik bildiriminde ya da dizin imzasında görünebilir.", + "require_call_may_be_converted_to_an_import_80005": "'require' çağrısı bir import olarak dönüştürülebilir.", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' seçeneği ayarlandı, '{0}' göreli modül adını çözümlemek için bu değer kullanılıyor.", "super_can_only_be_referenced_in_a_derived_class_2335": "'super' öğesine yalnızca bir türetilmiş sınıfta başvurulabilir.", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' değerine yalnızca türetilen sınıfların üyelerinde ya da nesne değişmez ifadelerinde başvurulabilir.", diff --git a/lib/tsc.js b/lib/tsc.js index b10e120519b..f39c393bfd1 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -28,564 +28,18 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook }; var ts; (function (ts) { - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); - var SyntaxKind; - (function (SyntaxKind) { - SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; - SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; - SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; - SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; - SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; - SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; - SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; - SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; - SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; - SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; - SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; - SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; - SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; - SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; - SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; - SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; - SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 142] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 143] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 144] = "OfKeyword"; - SyntaxKind[SyntaxKind["QualifiedName"] = 145] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 146] = "ComputedPropertyName"; - SyntaxKind[SyntaxKind["TypeParameter"] = 147] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 148] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 149] = "Decorator"; - SyntaxKind[SyntaxKind["PropertySignature"] = 150] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 151] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 152] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 153] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 154] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 155] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 156] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 157] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 158] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 159] = "IndexSignature"; - SyntaxKind[SyntaxKind["TypePredicate"] = 160] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 161] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 162] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 163] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 164] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 165] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 166] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 167] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 168] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 169] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 170] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 171] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 172] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 173] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 174] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 175] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 176] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 177] = "LiteralType"; - SyntaxKind[SyntaxKind["ImportType"] = 178] = "ImportType"; - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 179] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 180] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 181] = "BindingElement"; - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 182] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 183] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 184] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 185] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 186] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 187] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 188] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 189] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 190] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 191] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 192] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 193] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 194] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 195] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 196] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 197] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 198] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 199] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 200] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 201] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 202] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 203] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 204] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 205] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 206] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 207] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 208] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 209] = "MetaProperty"; - SyntaxKind[SyntaxKind["TemplateSpan"] = 210] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 211] = "SemicolonClassElement"; - SyntaxKind[SyntaxKind["Block"] = 212] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 213] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 214] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 215] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 216] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 217] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 218] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 219] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 220] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 221] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 222] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 223] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 224] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 225] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 226] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 227] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 228] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 229] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 230] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 231] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 232] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 233] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 234] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 235] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 236] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 237] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 238] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 239] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 240] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 241] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 242] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 243] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 244] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 245] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 246] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 247] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 248] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 249] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 250] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 251] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 252] = "MissingDeclaration"; - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 253] = "ExternalModuleReference"; - SyntaxKind[SyntaxKind["JsxElement"] = 254] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 255] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 256] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 257] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 258] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 259] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 260] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 261] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 262] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 263] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 264] = "JsxExpression"; - SyntaxKind[SyntaxKind["CaseClause"] = 265] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 266] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 267] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 268] = "CatchClause"; - SyntaxKind[SyntaxKind["PropertyAssignment"] = 269] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 270] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 271] = "SpreadAssignment"; - SyntaxKind[SyntaxKind["EnumMember"] = 272] = "EnumMember"; - SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle"; - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType"; - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; - SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 144] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 160] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 178] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; - SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 144] = "LastToken"; - SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; - SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; - SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; - SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; - SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword"; - })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); - var NodeFlags; - (function (NodeFlags) { - NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Let"] = 1] = "Let"; - NodeFlags[NodeFlags["Const"] = 2] = "Const"; - NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; - NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; - NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; - NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; - NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; - NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; - NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; - NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; - NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; - NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; - NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; - NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; - NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; - NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; - NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; - NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; - NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta"; - NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; - NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; - NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; - NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; - NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; - NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; - NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags"; - NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; - NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags"; - })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); - var ModifierFlags; - (function (ModifierFlags) { - ModifierFlags[ModifierFlags["None"] = 0] = "None"; - ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; - ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; - ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; - ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; - ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; - ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; - ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; - ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; - ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; - ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; - ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; - ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; - ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; - ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; - ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 3071] = "All"; - })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); - var JsxFlags; - (function (JsxFlags) { - JsxFlags[JsxFlags["None"] = 0] = "None"; - JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; - JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; - JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; - })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); - var RelationComparisonResult; - (function (RelationComparisonResult) { - RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; - RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; - RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; - })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); - var GeneratedIdentifierFlags; - (function (GeneratedIdentifierFlags) { - GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel"; - })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); - var TokenFlags; - (function (TokenFlags) { - TokenFlags[TokenFlags["None"] = 0] = "None"; - TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; - TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; - TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; - TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; - TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; - TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; - TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; - TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; - TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; - TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; - TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; - TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; - })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); - var FlowFlags; - (function (FlowFlags) { - FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; - FlowFlags[FlowFlags["Start"] = 2] = "Start"; - FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; - FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; - FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; - FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; - FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; - FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; - FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; - FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; - FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; - FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; - FlowFlags[FlowFlags["Label"] = 12] = "Label"; - FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; - })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; - var StructureIsReused; - (function (StructureIsReused) { - StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; - StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; - StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; - })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); - var UnionReduction; - (function (UnionReduction) { - UnionReduction[UnionReduction["None"] = 0] = "None"; - UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; - UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; - })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); - var NodeBuilderFlags; - (function (NodeBuilderFlags) { - NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; - NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; - NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; - NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; - NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; - NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; - NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; - NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; - NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; - NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; - NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; - })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); - var TypeFormatFlags; - (function (TypeFormatFlags) { - TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; - })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); - var SymbolFormatFlags; - (function (SymbolFormatFlags) { - SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; - SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; - SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; - SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; - SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; - })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); - var SymbolAccessibility; - (function (SymbolAccessibility) { - SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; - SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; - SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; - })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); - var SyntheticSymbolKind; - (function (SyntheticSymbolKind) { - SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; - SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; - })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); - var TypePredicateKind; - (function (TypePredicateKind) { - TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; - TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; - })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -600,269 +54,6 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var SymbolFlags; - (function (SymbolFlags) { - SymbolFlags[SymbolFlags["None"] = 0] = "None"; - SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; - SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; - SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; - SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; - SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; - SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; - SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; - SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; - SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; - SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; - SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; - SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; - SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; - SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; - SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; - SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; - SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; - SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; - SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; - SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; - SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; - SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; - SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; - SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; - SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; - SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; - SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; - SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; - SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; - SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; - SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; - SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; - SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; - SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; - SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; - SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; - SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; - SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; - SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; - SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; - SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; - SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; - SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; - SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; - SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; - SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; - SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; - })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); - var EnumKind; - (function (EnumKind) { - EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; - EnumKind[EnumKind["Literal"] = 1] = "Literal"; - })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); - var CheckFlags; - (function (CheckFlags) { - CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; - CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; - CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; - CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; - CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; - CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; - CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; - CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; - CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; - CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; - CheckFlags[CheckFlags["Late"] = 1024] = "Late"; - CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; - })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); - var InternalSymbolName; - (function (InternalSymbolName) { - InternalSymbolName["Call"] = "__call"; - InternalSymbolName["Constructor"] = "__constructor"; - InternalSymbolName["New"] = "__new"; - InternalSymbolName["Index"] = "__index"; - InternalSymbolName["ExportStar"] = "__export"; - InternalSymbolName["Global"] = "__global"; - InternalSymbolName["Missing"] = "__missing"; - InternalSymbolName["Type"] = "__type"; - InternalSymbolName["Object"] = "__object"; - InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; - InternalSymbolName["Class"] = "__class"; - InternalSymbolName["Function"] = "__function"; - InternalSymbolName["Computed"] = "__computed"; - InternalSymbolName["Resolving"] = "__resolving__"; - InternalSymbolName["ExportEquals"] = "export="; - InternalSymbolName["Default"] = "default"; - })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); - var NodeCheckFlags; - (function (NodeCheckFlags) { - NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; - NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; - NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; - NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; - NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; - NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; - NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; - NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; - NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; - NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; - NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; - })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); - var TypeFlags; - (function (TypeFlags) { - TypeFlags[TypeFlags["Any"] = 1] = "Any"; - TypeFlags[TypeFlags["String"] = 2] = "String"; - TypeFlags[TypeFlags["Number"] = 4] = "Number"; - TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; - TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["UniqueESSymbol"] = 1024] = "UniqueESSymbol"; - TypeFlags[TypeFlags["Void"] = 2048] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 8192] = "Null"; - TypeFlags[TypeFlags["Never"] = 16384] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 65536] = "Object"; - TypeFlags[TypeFlags["Union"] = 131072] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 524288] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess"; - TypeFlags[TypeFlags["Conditional"] = 2097152] = "Conditional"; - TypeFlags[TypeFlags["Substitution"] = 4194304] = "Substitution"; - TypeFlags[TypeFlags["FreshLiteral"] = 8388608] = "FreshLiteral"; - TypeFlags[TypeFlags["ContainsWideningType"] = 16777216] = "ContainsWideningType"; - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 33554432] = "ContainsObjectLiteral"; - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive"; - TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType"; - TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 13536] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; - TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique"; - TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy"; - TypeFlags[TypeFlags["Intrinsic"] = 134249103] = "Intrinsic"; - TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike"; - TypeFlags[TypeFlags["VoidLike"] = 6144] = "VoidLike"; - TypeFlags[TypeFlags["DisjointDomains"] = 134233854] = "DisjointDomains"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType"; - TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable"; - TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 7372800] = "InstantiableNonPrimitive"; - TypeFlags[TypeFlags["InstantiablePrimitive"] = 524288] = "InstantiablePrimitive"; - TypeFlags[TypeFlags["Instantiable"] = 7897088] = "Instantiable"; - TypeFlags[TypeFlags["StructuredOrInstantiable"] = 8355840] = "StructuredOrInstantiable"; - TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit"; - TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening"; - TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags"; - TypeFlags[TypeFlags["NonWideningType"] = 16777216] = "NonWideningType"; - TypeFlags[TypeFlags["Wildcard"] = 33554432] = "Wildcard"; - TypeFlags[TypeFlags["EmptyObject"] = 67108864] = "EmptyObject"; - TypeFlags[TypeFlags["ConstructionFlags"] = 117440512] = "ConstructionFlags"; - })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); - var ObjectFlags; - (function (ObjectFlags) { - ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; - ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; - ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; - ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; - ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; - ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; - ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; - ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; - ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; - ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; - })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); - var Variance; - (function (Variance) { - Variance[Variance["Invariant"] = 0] = "Invariant"; - Variance[Variance["Covariant"] = 1] = "Covariant"; - Variance[Variance["Contravariant"] = 2] = "Contravariant"; - Variance[Variance["Bivariant"] = 3] = "Bivariant"; - Variance[Variance["Independent"] = 4] = "Independent"; - })(Variance = ts.Variance || (ts.Variance = {})); - var SignatureKind; - (function (SignatureKind) { - SignatureKind[SignatureKind["Call"] = 0] = "Call"; - SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; - })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); - var IndexKind; - (function (IndexKind) { - IndexKind[IndexKind["String"] = 0] = "String"; - IndexKind[IndexKind["Number"] = 1] = "Number"; - })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); - var InferencePriority; - (function (InferencePriority) { - InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; - })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); - var InferenceFlags; - (function (InferenceFlags) { - InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; - })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); - var Ternary; - (function (Ternary) { - Ternary[Ternary["False"] = 0] = "False"; - Ternary[Ternary["Maybe"] = 1] = "Maybe"; - Ternary[Ternary["True"] = -1] = "True"; - })(Ternary = ts.Ternary || (ts.Ternary = {})); - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -891,390 +82,6 @@ var ts; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); - var JsxEmit; - (function (JsxEmit) { - JsxEmit[JsxEmit["None"] = 0] = "None"; - JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; - JsxEmit[JsxEmit["React"] = 2] = "React"; - JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; - })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); - var NewLineKind; - (function (NewLineKind) { - NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; - NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; - })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); - var ScriptKind; - (function (ScriptKind) { - ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; - ScriptKind[ScriptKind["JS"] = 1] = "JS"; - ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; - ScriptKind[ScriptKind["TS"] = 3] = "TS"; - ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; - ScriptKind[ScriptKind["External"] = 5] = "External"; - ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; - })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); - var ScriptTarget; - (function (ScriptTarget) { - ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; - ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; - ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; - ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; - ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; - ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; - ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; - ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; - })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); - var LanguageVariant; - (function (LanguageVariant) { - LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; - LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; - })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); - var WatchDirectoryFlags; - (function (WatchDirectoryFlags) { - WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; - WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; - })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); - var CharacterCodes; - (function (CharacterCodes) { - CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; - CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; - CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; - CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; - CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; - CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; - CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; - CharacterCodes[CharacterCodes["space"] = 32] = "space"; - CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; - CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; - CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; - CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; - CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; - CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; - CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; - CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; - CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; - CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; - CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; - CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; - CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; - CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; - CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; - CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; - CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; - CharacterCodes[CharacterCodes["_"] = 95] = "_"; - CharacterCodes[CharacterCodes["$"] = 36] = "$"; - CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; - CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; - CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; - CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; - CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; - CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; - CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; - CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; - CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; - CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; - CharacterCodes[CharacterCodes["a"] = 97] = "a"; - CharacterCodes[CharacterCodes["b"] = 98] = "b"; - CharacterCodes[CharacterCodes["c"] = 99] = "c"; - CharacterCodes[CharacterCodes["d"] = 100] = "d"; - CharacterCodes[CharacterCodes["e"] = 101] = "e"; - CharacterCodes[CharacterCodes["f"] = 102] = "f"; - CharacterCodes[CharacterCodes["g"] = 103] = "g"; - CharacterCodes[CharacterCodes["h"] = 104] = "h"; - CharacterCodes[CharacterCodes["i"] = 105] = "i"; - CharacterCodes[CharacterCodes["j"] = 106] = "j"; - CharacterCodes[CharacterCodes["k"] = 107] = "k"; - CharacterCodes[CharacterCodes["l"] = 108] = "l"; - CharacterCodes[CharacterCodes["m"] = 109] = "m"; - CharacterCodes[CharacterCodes["n"] = 110] = "n"; - CharacterCodes[CharacterCodes["o"] = 111] = "o"; - CharacterCodes[CharacterCodes["p"] = 112] = "p"; - CharacterCodes[CharacterCodes["q"] = 113] = "q"; - CharacterCodes[CharacterCodes["r"] = 114] = "r"; - CharacterCodes[CharacterCodes["s"] = 115] = "s"; - CharacterCodes[CharacterCodes["t"] = 116] = "t"; - CharacterCodes[CharacterCodes["u"] = 117] = "u"; - CharacterCodes[CharacterCodes["v"] = 118] = "v"; - CharacterCodes[CharacterCodes["w"] = 119] = "w"; - CharacterCodes[CharacterCodes["x"] = 120] = "x"; - CharacterCodes[CharacterCodes["y"] = 121] = "y"; - CharacterCodes[CharacterCodes["z"] = 122] = "z"; - CharacterCodes[CharacterCodes["A"] = 65] = "A"; - CharacterCodes[CharacterCodes["B"] = 66] = "B"; - CharacterCodes[CharacterCodes["C"] = 67] = "C"; - CharacterCodes[CharacterCodes["D"] = 68] = "D"; - CharacterCodes[CharacterCodes["E"] = 69] = "E"; - CharacterCodes[CharacterCodes["F"] = 70] = "F"; - CharacterCodes[CharacterCodes["G"] = 71] = "G"; - CharacterCodes[CharacterCodes["H"] = 72] = "H"; - CharacterCodes[CharacterCodes["I"] = 73] = "I"; - CharacterCodes[CharacterCodes["J"] = 74] = "J"; - CharacterCodes[CharacterCodes["K"] = 75] = "K"; - CharacterCodes[CharacterCodes["L"] = 76] = "L"; - CharacterCodes[CharacterCodes["M"] = 77] = "M"; - CharacterCodes[CharacterCodes["N"] = 78] = "N"; - CharacterCodes[CharacterCodes["O"] = 79] = "O"; - CharacterCodes[CharacterCodes["P"] = 80] = "P"; - CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; - CharacterCodes[CharacterCodes["R"] = 82] = "R"; - CharacterCodes[CharacterCodes["S"] = 83] = "S"; - CharacterCodes[CharacterCodes["T"] = 84] = "T"; - CharacterCodes[CharacterCodes["U"] = 85] = "U"; - CharacterCodes[CharacterCodes["V"] = 86] = "V"; - CharacterCodes[CharacterCodes["W"] = 87] = "W"; - CharacterCodes[CharacterCodes["X"] = 88] = "X"; - CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; - CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; - CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; - CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; - CharacterCodes[CharacterCodes["at"] = 64] = "at"; - CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; - CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; - CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; - CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; - CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; - CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; - CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; - CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; - CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; - CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; - CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; - CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; - CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; - CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; - CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; - CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; - CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; - CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; - CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; - CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; - CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; - CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; - CharacterCodes[CharacterCodes["question"] = 63] = "question"; - CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; - CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; - CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; - CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; - CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; - CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; - CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; - CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; - CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; - })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); - var Extension; - (function (Extension) { - Extension["Ts"] = ".ts"; - Extension["Tsx"] = ".tsx"; - Extension["Dts"] = ".d.ts"; - Extension["Js"] = ".js"; - Extension["Jsx"] = ".jsx"; - Extension["Json"] = ".json"; - })(Extension = ts.Extension || (ts.Extension = {})); - var TransformFlags; - (function (TransformFlags) { - TransformFlags[TransformFlags["None"] = 0] = "None"; - TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; - TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; - TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; - TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; - TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; - TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; - TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; - TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; - })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); - var EmitFlags; - (function (EmitFlags) { - EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; - EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; - EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; - EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; - EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; - EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; - EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; - EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; - EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; - EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; - EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; - EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; - EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; - EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; - EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; - EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; - EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; - EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; - EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; - EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; - EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; - EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; - EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; - EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; - EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; - EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; - EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; - EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; - EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; - EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; - })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); - var ExternalEmitHelpers; - (function (ExternalEmitHelpers) { - ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; - ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; - ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; - ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; - ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; - ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; - ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; - ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; - ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; - ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; - ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; - ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; - ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; - ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; - })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); - var EmitHint; - (function (EmitHint) { - EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; - EmitHint[EmitHint["Expression"] = 1] = "Expression"; - EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; - EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; - })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; - ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; - ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; - ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; - ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); - var PragmaKindFlags; - (function (PragmaKindFlags) { - PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; - PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; - PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; - PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; - PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; - PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; - })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); function _contextuallyTypePragmas(args) { return args; } @@ -1612,8 +419,8 @@ var ts; return undefined; } ts.findLast = findLast; - function findIndex(array, predicate) { - for (var i = 0; i < array.length; i++) { + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -1621,6 +428,15 @@ var ts; return -1; } ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; function findMap(array, callback) { for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); @@ -1951,6 +767,23 @@ var ts; return false; } ts.some = some; + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; function concatenate(array1, array2) { if (!some(array2)) return array1; @@ -2141,6 +974,15 @@ var ts; return to; } ts.addRange = addRange; + function prependRange(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + to.unshift.apply(to, from); + return to; + } + ts.prependRange = prependRange; function pushIfUnique(array, toAdd, equalityComparer) { if (contains(array, toAdd, equalityComparer)) { return false; @@ -2338,17 +1180,18 @@ var ts; } ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { + var _a; var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { result.push(map ? map(value) : value); } return result; - var _b; } ts.arrayFrom = arrayFrom; function forEachEntry(map, callback) { + var _a; var iterator = map.entries(); - for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { var key = pair[0], value = pair[1]; var result = callback(value, key); if (result) { @@ -2356,19 +1199,18 @@ var ts; } } return undefined; - var _b; } ts.forEachEntry = forEachEntry; function forEachKey(map, callback) { + var _a; var iterator = map.keys(); - for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { var result = callback(key); if (result) { return result; } } return undefined; - var _b; } ts.forEachKey = forEachKey; function copyEntries(source, target) { @@ -2837,11 +1679,11 @@ var ts; comparer(a[key], b[key]); } ts.compareProperties = compareProperties; - function getDiagnosticFileName(diagnostic) { - return diagnostic.file ? diagnostic.file.fileName : undefined; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; } function compareDiagnostics(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -2869,90 +1711,6 @@ var ts; } return text1 ? 1 : -1; } - function normalizeSlashes(path) { - return path.replace(/\\/g, "/"); - } - ts.normalizeSlashes = normalizeSlashes; - function getRootLength(path) { - if (path.charCodeAt(0) === 47) { - if (path.charCodeAt(1) !== 47) - return 1; - var p1 = path.indexOf("/", 2); - if (p1 < 0) - return 2; - var p2 = path.indexOf("/", p1 + 1); - if (p2 < 0) - return p1 + 1; - return p2 + 1; - } - if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92) - return 3; - } - if (path.lastIndexOf("file:///", 0) === 0) { - return "file:///".length; - } - var idx = path.indexOf("://"); - if (idx !== -1) { - return idx + "://".length; - } - return 0; - } - ts.getRootLength = getRootLength; - ts.directorySeparator = "/"; - var directorySeparatorCharCode = 47; - function getNormalizedParts(normalizedSlashedPath, rootLength) { - var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); - var normalized = []; - for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { - var part = parts_1[_i]; - if (part !== ".") { - if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { - normalized.pop(); - } - else { - if (part) { - normalized.push(part); - } - } - } - } - return normalized; - } - function normalizePath(path) { - return normalizePathAndParts(path).path; - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - var root = path.substr(0, rootLength); - var parts = getNormalizedParts(path, rootLength); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function pathEndsWithDirectorySeparator(path) { - return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; - } - ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; - function getDirectoryPath(path) { - return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function isUrl(path) { - return path && !isRootedDiskPath(path) && stringContains(path, "://"); - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -2984,6 +1742,10 @@ var ts; : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; } @@ -3003,181 +1765,351 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 && charCode <= 122) || + (charCode >= 65 && charCode <= 90); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58) + return start + 1; + if (ch0 === 37 && url.charCodeAt(start + 1) === 51) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 || ch2 === 65) + return start + 3; + } + return -1; + } + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + if (ch0 === 47 || ch0 === 92) { + if (path.charCodeAt(1) !== ch0) + return 1; + var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; + return p1 + 1; + } + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 || ch2 === 92) + return 3; + if (path.length === 2) + return 2; + } + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47) { + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); + } + return ~path.length; + } + return 0; + } + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function normalizePath(path) { + return resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; function isRootedDiskPath(path) { - return path && getRootLength(path) !== 0; + return getEncodedRootLength(path) > 0; } ts.isRootedDiskPath = isRootedDiskPath; + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); } ts.convertToRelativePath = convertToRelativePath; - function normalizedPathComponents(path, rootLength) { - var normalizedParts = getNormalizedParts(path, rootLength); - return [path.substr(0, rootLength)].concat(normalizedParts); + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); } - function getNormalizedPathComponents(path, currentDirectory) { - path = normalizeSlashes(path); + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); var rootLength = getRootLength(path); - if (rootLength === 0) { - path = combinePaths(normalizeSlashes(currentDirectory), path); - rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + function reducePathComponents(components) { + if (!some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); } - return normalizedPathComponents(path, rootLength); + return reduced; + } + ts.reducePathComponents = reducePathComponents; + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); } ts.getNormalizedPathComponents = getNormalizedPathComponents; function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); } ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getNormalizedPathFromPathComponents(pathComponents) { - if (pathComponents && pathComponents.length) { - return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); - } + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + if (pathComponents.length === 1) + return root; + return root + pathComponents.slice(1).join(ts.directorySeparator); } - ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; - function getNormalizedPathComponentsOfUrl(url) { - var urlLength = url.length; - var rootLength = url.indexOf("://") + "://".length; - while (rootLength < urlLength) { - if (url.charCodeAt(rootLength) === 47) { - rootLength++; - } - else { + ts.getPathFromPathComponents = getPathFromPathComponents; + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) break; - } } - if (rootLength === urlLength) { - return [url]; + if (start === 0) { + return toComponents; } - var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); - if (indexOfNextSlash !== -1) { - rootLength = indexOfNextSlash + 1; - return normalizedPathComponents(url, rootLength); - } - else { - return [url + ts.directorySeparator]; + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); } + return [""].concat(relative, components); } - function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { - if (isUrl(pathOrUrl)) { - return getNormalizedPathComponentsOfUrl(pathOrUrl); - } - else { - return getNormalizedPathComponents(pathOrUrl, currentDirectory); - } + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - directoryComponents.pop(); + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; } - var joinStartIndex; - for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { - break; - } - } - if (joinStartIndex) { - var relativePath = ""; - var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); - for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (directoryComponents[joinStartIndex] !== "") { - relativePath = relativePath + ".." + ts.directorySeparator; - } - } - return relativePath + relativePathComponents.join(ts.directorySeparator); - } - var absolutePath = getNormalizedPathFromPathComponents(pathComponents); - if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { - absolutePath = "file:///" + absolutePath; - } - return absolutePath; + return getPathFromPathComponents(pathComponents); } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function getRelativePath(path, directoryPath, getCanonicalFileName) { - var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ensurePathIsRelative(relativePath); + function ensurePathIsNonModuleName(path) { + return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path; } - ts.getRelativePath = getRelativePath; - function ensurePathIsRelative(path) { - return !pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsRelative = ensurePathIsRelative; - function getBaseFileName(path) { - if (path === undefined) { - return undefined; - } - var i = path.lastIndexOf(ts.directorySeparator); - return i < 0 ? path : path.substring(i + 1); + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; } ts.getBaseFileName = getBaseFileName; - function combinePaths(path1, path2) { - if (!(path1 && path1.length)) - return path2; - if (!(path2 && path2.length)) - return path1; - if (getRootLength(path2) !== 0) - return path2; - if (path1.charAt(path1.length - 1) === ts.directorySeparator) - return path1 + path2; - return path1 + ts.directorySeparator + path2; + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; } ts.combinePaths = combinePaths; + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 || ch === 92; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function removeTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) === ts.directorySeparator) { + if (hasTrailingDirectorySeparator(path)) { return path.substr(0, path.length - 1); } return path; } ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; function ensureTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) !== ts.directorySeparator) { + if (!hasTrailingDirectorySeparator(path)) { return path + ts.directorySeparator; } return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - function comparePaths(a, b, currentDirectory, ignoreCase) { + function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0; if (a === undefined) return -1; if (b === undefined) return 1; - a = removeTrailingDirectorySeparator(a); - b = removeTrailingDirectorySeparator(b); - var aComponents = getNormalizedPathComponents(a, currentDirectory); - var bComponents = getNormalizedPathComponents(b, currentDirectory); + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - var comparer = getStringComparer(ignoreCase); for (var i = 0; i < sharedLength; i++) { - var result = comparer(aComponents[i], bComponents[i]); + var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); if (result !== 0) { return result; } } return compareValues(aComponents.length, bComponents.length); } + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, getStringComparer(ignoreCase)); + } ts.comparePaths = comparePaths; function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } if (parent === undefined || child === undefined) return false; if (parent === child) return true; - parent = removeTrailingDirectorySeparator(parent); - child = removeTrailingDirectorySeparator(child); - if (parent === child) - return true; - var parentComponents = getNormalizedPathComponents(parent, currentDirectory); - var childComponents = getNormalizedPathComponents(child, currentDirectory); + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); if (childComponents.length < parentComponents.length) { return false; } - var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; + var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer; if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } @@ -3454,13 +2386,17 @@ var ts; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { - var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { - return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; + function isJavaScriptLike(scriptKind) { + return scriptKind === 1 || scriptKind === 2; + } function hasJavaScriptFileExtension(fileName) { return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } @@ -3482,13 +2418,6 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; - var ExtensionPriority; - (function (ExtensionPriority) { - ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; - ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; - ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; - ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; - })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -3519,7 +2448,7 @@ var ts; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; + var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx", ".json"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { var ext = extensionsToRemove_1[_i]; @@ -3540,9 +2469,14 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return (removeFileExtension(path) + newExtension); + return changeAnyExtension(path, newExtension, extensionsToRemove, false); } ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; function removeMinAndVersionNumbers(fileName) { var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); @@ -3590,13 +2524,6 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - var AssertionLevel; - (function (AssertionLevel) { - AssertionLevel[AssertionLevel["None"] = 0] = "None"; - AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; - AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; - AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; - })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -3801,6 +2728,10 @@ var ts; return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } ts.extensionIsTypeScript = extensionIsTypeScript; + function resolutionExtensionIsTypeScriptOrJson(ext) { + return extensionIsTypeScript(ext) || ext === ".json"; + } + ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); if (ext !== undefined) { @@ -3817,12 +2748,32 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPath(path) { + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive); + } var baseFileName = getBaseFileName(path); var extensionIndex = baseFileName.lastIndexOf("."); if (extensionIndex >= 0) { return baseFileName.substring(extensionIndex); } + return ""; } ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -3915,12 +2866,12 @@ var ts; ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; ts.missingFileModifiedTime = new Date(0); function createPollingIntervalBasedLevels(levels) { + var _a; return _a = {}, _a[PollingInterval.Low] = levels.Low, _a[PollingInterval.Medium] = levels.Medium, _a[PollingInterval.High] = levels.High, _a; - var _a; } var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); @@ -4193,11 +3144,6 @@ var ts; var isNode4OrLater = nodeVersion >= 4; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - var FileSystemEntryKind; - (function (FileSystemEntryKind) { - FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; - FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; - })(FileSystemEntryKind || (FileSystemEntryKind = {})); var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; var tscWatchFile = process.env.TSC_WATCHFILE; var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; @@ -4237,6 +3183,7 @@ var ts; readDirectory: readDirectory, getModifiedTime: getModifiedTime, createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, getMemoryUsage: function () { if (global.gc) { global.gc(); @@ -4609,6 +3556,11 @@ var ts; hash.update(data); return hash.digest("hex"); } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -4911,7 +3863,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5388,6 +4340,7 @@ var ts; Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5571,6 +4524,17 @@ var ts; Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5669,6 +4633,7 @@ var ts; Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5732,6 +4697,12 @@ var ts; Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), }; })(ts || (ts = {})); var ts; @@ -7298,11 +6269,10 @@ var ts; } } function scanJSDocToken() { + startPos = tokenPos = pos; if (pos >= end) { return token = 1; } - startPos = pos; - tokenPos = pos; var ch = text.charCodeAt(pos); pos++; switch (ch) { @@ -7659,7 +6629,7 @@ var ts; if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 294 && node._children.length > 0) { + if (node.kind === 298 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -7834,12 +6804,12 @@ var ts; case 159: case 162: case 163: - case 281: + case 283: case 234: case 204: case 235: case 236: - case 291: + case 295: case 233: case 153: case 154: @@ -7847,6 +6817,9 @@ var ts; case 156: case 191: case 192: + case 291: + case 296: + case 287: return true; default: ts.assertTypeIsNever(node); @@ -7869,6 +6842,12 @@ var ts; case 243: case 242: case 213: + case 234: + case 233: + case 238: + case 236: + case 235: + case 237: return true; default: return false; @@ -7880,13 +6859,7 @@ var ts; } ts.isAnyImportOrReExport = isAnyImportOrReExport; function getEnclosingBlockScopeContainer(node) { - var current = node.parent; - while (current) { - if (isBlockScope(current, current.parent)) { - return current; - } - current = current.parent; - } + return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function declarationNameToString(name) { @@ -7996,6 +6969,8 @@ var ts; case 155: case 156: case 236: + case 151: + case 150: errorNode = node.name; break; case 192: @@ -8023,6 +6998,10 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6; + } + ts.isJsonSourceFile = isJsonSourceFile; function isConstEnumDeclaration(node) { return node.kind === 237 && isConst(node); } @@ -8334,6 +7313,23 @@ var ts; }); } ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.isObjectLiteralExpression(expression) && expression; + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral && + ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -8671,6 +7667,10 @@ var ts; return node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJsonFile(node) { + return node && !!(node.flags & 16777216); + } + ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { return node && !!(node.flags & 2097152); } @@ -8848,6 +7848,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243: case 249: @@ -8857,12 +7861,13 @@ var ts; case 186: return node.parent; case 177: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243: @@ -8911,12 +7916,20 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 281 && + return node.kind === 283 && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 296 || node.kind === 291; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && @@ -8938,6 +7951,8 @@ var ts; return v && v.initializer; case 151: return node.initializer; + case 269: + return node.initializer; } } function getSingleVariableOfVariableStatement(node) { @@ -8951,9 +7966,9 @@ var ts; node.body.kind === 238 && node.body; } - function getJSDocCommentsAndTags(node) { + function getJSDocCommentsAndTags(hostNode) { var result; - getJSDocCommentsAndTagsWorker(node); + getJSDocCommentsAndTagsWorker(hostNode); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; @@ -8962,8 +7977,7 @@ var ts; if (parent.kind === 269 || parent.kind === 151 || getNestedModuleDeclaration(parent)) { getJSDocCommentsAndTagsWorker(parent); } - if (parent.parent && - (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { + if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) { getJSDocCommentsAndTagsWorker(parent.parent); } if (parent.parent && parent.parent.parent && @@ -8972,15 +7986,15 @@ var ts; getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } - if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 || - ts.isBinaryExpression(parent) && getSpecialPropertyAssignmentKind(parent) !== 0 || + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 || node.kind === 184 && node.parent && node.parent.kind === 215) { getJSDocCommentsAndTagsWorker(parent); } if (node.kind === 148) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -9006,7 +8020,10 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - var host = getJSDocHost(node); + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || @@ -9015,18 +8032,9 @@ var ts; host; return decl && ts.isFunctionLike(decl) ? decl : undefined; } - ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; function getJSDocHost(node) { - while (node.parent.kind === 284) { - if (node.parent.parent.kind === 292) { - node = node.parent.parent; - } - else { - node = node.parent.parent.parent; - } - } - ts.Debug.assert(node.parent.kind === 283); - return node.parent.parent; + return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent; } ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { @@ -9041,15 +8049,10 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282; + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || type && type.kind === 284; } ts.isRestParameter = isRestParameter; - var AssignmentKind; - (function (AssignmentKind) { - AssignmentKind[AssignmentKind["None"] = 0] = "None"; - AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; - AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; - })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); function getAssignmentTargetKind(node) { var parent = node.parent; while (true) { @@ -9172,8 +8175,14 @@ var ts; if (ts.isDeclaration(name.parent)) { return name.parent.name === name; } - var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + else if (ts.isQualifiedName(name.parent)) { + var tag = name.parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + } + else { + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + } default: return false; } @@ -9303,14 +8312,6 @@ var ts; return 2 <= token && token <= 7; } ts.isTrivia = isTrivia; - var FunctionFlags; - (function (FunctionFlags) { - FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; - FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; - FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; - })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { if (!node) { return 4; @@ -9458,11 +8459,6 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - var Associativity; - (function (Associativity) { - Associativity[Associativity["Left"] = 0] = "Left"; - Associativity[Associativity["Right"] = 1] = "Right"; - })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); var hasArguments = expression.kind === 187 && expression.arguments !== undefined; @@ -9523,7 +8519,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 297: + case 301: return 0; case 203: return 1; @@ -9834,8 +8830,8 @@ var ts; }; } ts.createTextWriter = createTextWriter; - function getResolvedExternalModuleName(host, file) { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { @@ -9846,12 +8842,13 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - function getExternalModuleNameFromPath(host, fileName) { + function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); - return ts.removeFileExtension(relativePath); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { @@ -9933,7 +8930,7 @@ var ts; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { - if (signature.parameters.length) { + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { var thisParameter = signature.parameters[0]; if (parameterIsThisKeyword(thisParameter)) { return thisParameter; @@ -10010,16 +9007,33 @@ var ts; } ts.getTypeAnnotationNode = getTypeAnnotationNode; function getEffectiveReturnTypeNode(node) { + if (ts.isJSDocSignature(node)) { + return node.type && node.type.typeExpression && node.type.typeExpression.type; + } return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getEffectiveTypeParameterDeclarations(node) { - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 285); + var templateTags = ts.flatMap(ts.filter(node.parent.tags, ts.isJSDocTemplateTag), function (tag) { return tag.typeParameters; }); + var templateTagNodes = templateTags; + templateTagNodes.pos = templateTagNodes.length > 0 ? ts.first(templateTagNodes).pos : node.pos; + templateTagNodes.end = templateTagNodes.length > 0 ? ts.last(templateTagNodes).end : node.end; + templateTagNodes.hasTrailingComma = false; + return templateTagNodes; + } + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; + var tag = ts.find(ts.getJSDocTags(node), function (tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 && tag.parent.tags.some(isJSDocTypeAlias)); + }); + return (tag && tag.typeParameters) || ts.emptyArray; } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; function getEffectiveSetAccessorTypeAnnotationNode(node) { @@ -10644,12 +9658,6 @@ var ts; return accessKind(node) !== 0; } ts.isWriteAccess = isWriteAccess; - var AccessKind; - (function (AccessKind) { - AccessKind[AccessKind["Read"] = 0] = "Read"; - AccessKind[AccessKind["Write"] = 1] = "Write"; - AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; - })(AccessKind || (AccessKind = {})); function accessKind(node) { var parent = node.parent; if (!parent) @@ -11144,8 +10152,8 @@ var ts; break; case 71: return declaration; - case 293: - case 288: { + case 297: + case 292: { var name = declaration.name; if (name.kind === 145) { return name.right; @@ -11164,7 +10172,9 @@ var ts; return undefined; } } - case 292: + case 291: + return declaration.name; + case 296: return getNameOfJSDocTypedef(declaration); case 248: { var expression = declaration.expression; @@ -11252,7 +10262,9 @@ var ts; function getJSDocTags(node) { var tags = node.jsDocCache; if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); } return tags; } @@ -11362,6 +10374,10 @@ var ts; return node.kind === 159; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 156 || node.kind === 155; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isTypePredicateNode(node) { return node.kind === 160; } @@ -11487,7 +10503,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296) { + while (node.kind === 300) { node = node.expression; } return node; @@ -11834,85 +10850,93 @@ var ts; } ts.isBundle = isBundle; function isJSDocTypeExpression(node) { - return node.kind === 275; + return node.kind === 277; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 276; + return node.kind === 278; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 277; + return node.kind === 279; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 278; + return node.kind === 280; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 279; + return node.kind === 281; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 280; + return node.kind === 282; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 281; + return node.kind === 283; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 282; + return node.kind === 284; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 283; + return node.kind === 285; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 286; + return node.kind === 289; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 287; + return node.kind === 290; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { - return node.kind === 288; + return node.kind === 292; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 289; + return node.kind === 293; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 290; + return node.kind === 294; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 291; + return node.kind === 295; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 292; + return node.kind === 296; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 293; + return node.kind === 297; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 293 || node.kind === 288; + return node.kind === 297 || node.kind === 292; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 284; + return node.kind === 286; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 291; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 287; + } + ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); (function (ts) { function isSyntaxList(n) { - return n.kind === 294; + return n.kind === 298; } ts.isSyntaxList = isSyntaxList; function isNode(node) { @@ -12034,10 +11058,11 @@ var ts; switch (kind) { case 152: case 157: + case 287: case 158: case 159: case 162: - case 281: + case 283: case 163: return true; default: @@ -12116,13 +11141,13 @@ var ts; || kind === 95 || kind === 131 || kind === 206 - || kind === 276 - || kind === 277 || kind === 278 || kind === 279 || kind === 280 || kind === 281 - || kind === 282; + || kind === 282 + || kind === 283 + || kind === 284; } function isTypeNode(node) { return isTypeNodeKind(node.kind); @@ -12309,8 +11334,8 @@ var ts; case 203: case 207: case 205: - case 297: - case 296: + case 301: + case 300: return true; default: return isUnaryExpressionKind(kind); @@ -12323,11 +11348,11 @@ var ts; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 296; + return node.kind === 300; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 295; + return node.kind === 299; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -12427,7 +11452,9 @@ var ts; || kind === 236 || kind === 147 || kind === 231 - || kind === 292; + || kind === 296 + || kind === 291 + || kind === 297; } function isDeclarationStatementKind(kind) { return kind === 233 @@ -12462,13 +11489,13 @@ var ts; || kind === 213 || kind === 218 || kind === 225 - || kind === 295 || kind === 299 - || kind === 298; + || kind === 303 + || kind === 302; } function isDeclaration(node) { if (node.kind === 147) { - return node.parent.kind !== 291 || ts.isInJavaScriptFile(node); + return node.parent.kind !== 295 || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -12546,15 +11573,15 @@ var ts; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isJSDocNode(node) { - return node.kind >= 275 && node.kind <= 293; + return node.kind >= 277 && node.kind <= 297; } ts.isJSDocNode = isJSDocNode; function isJSDocCommentContainingNode(node) { - return node.kind === 283 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node); + return node.kind === 285 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; function isJSDocTag(node) { - return node.kind >= 285 && node.kind <= 293; + return node.kind >= 288 && node.kind <= 297; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -12599,12 +11626,12 @@ var ts; case 231: case 233: case 236: - case 275: - case 278: - case 279: + case 277: case 280: case 281: case 282: + case 283: + case 284: return true; } return false; @@ -12672,16 +11699,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var SignatureFlags; - (function (SignatureFlags) { - SignatureFlags[SignatureFlags["None"] = 0] = "None"; - SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; - SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; - SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; - SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; - SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; - SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; - })(SignatureFlags || (SignatureFlags = {})); var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -13071,7 +12088,7 @@ var ts; return visitNode(cbNode, node.expression); case 252: return visitNodes(cbNode, cbNodes, node.decorators); - case 297: + case 301: return visitNodes(cbNode, cbNodes, node.elements); case 254: return visitNode(cbNode, node.openingElement) || @@ -13098,23 +12115,23 @@ var ts; visitNode(cbNode, node.expression); case 257: return visitNode(cbNode, node.tagName); - case 275: + case 277: return visitNode(cbNode, node.type); - case 279: - return visitNode(cbNode, node.type); - case 278: + case 281: return visitNode(cbNode, node.type); case 280: return visitNode(cbNode, node.type); - case 281: - return visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); case 282: return visitNode(cbNode, node.type); case 283: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 284: + return visitNode(cbNode, node.type); + case 285: return visitNodes(cbNode, cbNodes, node.tags); - case 288: - case 293: + case 292: + case 297: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -13123,17 +12140,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } + case 293: + return visitNode(cbNode, node.typeExpression); + case 294: + return visitNode(cbNode, node.typeExpression); case 289: - return visitNode(cbNode, node.typeExpression); - case 290: - return visitNode(cbNode, node.typeExpression); - case 286: return visitNode(cbNode, node.class); - case 291: + case 295: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 292: + case 296: if (node.typeExpression && - node.typeExpression.kind === 275) { + node.typeExpression.kind === 277) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -13141,7 +12158,16 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 284: + case 291: + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 287: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 286: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -13149,7 +12175,7 @@ var ts; } } return; - case 296: + case 300: return visitNode(cbNode, node.expression); } } @@ -13157,7 +12183,13 @@ var ts; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + var result; + if (languageVersion === 100) { + result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + } ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; @@ -13214,6 +12246,13 @@ var ts; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined); + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + return result_1; + } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); @@ -13229,23 +12268,54 @@ var ts; return isInvalid ? entityName : undefined; } Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function parseJsonText(fileName, sourceText) { - initializeState(sourceText, 2, undefined, 6); + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2; } + initializeState(sourceText, languageVersion, syntaxCursor, 6); sourceFile = createSourceFile(fileName, 2, 6, false); - var result = sourceFile; nextToken(); + var pos = getNodePos(); if (token() === 1) { + sourceFile.statements = createNodeArray([], pos, pos); sourceFile.endOfFileToken = parseTokenNode(); } - else if (token() === 17 || - lookAhead(function () { return token() === 9; })) { - result.jsonObject = parseObjectLiteralExpression(); + else { + var statement = createNode(215); + switch (token()) { + case 21: + statement.expression = parseArrayLiteralExpression(); + break; + case 101: + case 86: + case 95: + statement.expression = parseTokenNode(); + break; + case 38: + if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 56; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8: + case 9: + if (lookAhead(function () { return nextToken() !== 56; })) { + statement.expression = parseLiteralNode(); + break; + } + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); sourceFile.endOfFileToken = parseExpectedToken(1, ts.Diagnostics.Unexpected_token); } - else { - parseExpected(17); + if (setParentNodes) { + fixupParentReferences(sourceFile); } sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; clearState(); return result; } @@ -13268,9 +12338,11 @@ var ts; switch (scriptKind) { case 1: case 2: - case 6: contextFlags = 65536; break; + case 6: + contextFlags = 65536 | 16777216; + break; default: contextFlags = 0; break; @@ -14260,9 +13332,9 @@ var ts; return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(276); + var result = createNode(278); if (postFixEquals) { - return createJSDocPostfixType(280, result); + return createJSDocPostfixType(282, result); } else { nextToken(); @@ -14270,7 +13342,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(279); + var result = createNode(281); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -14284,18 +13356,18 @@ var ts; token() === 29 || token() === 58 || token() === 49) { - var result = createNode(277, pos); + var result = createNode(279, pos); return finishNode(result); } else { - var result = createNode(278, pos); + var result = createNode(280, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(281); + var result = createNodeWithJSDoc(283); nextToken(); fillSignature(56, 4 | 32, result); return finishNode(result); @@ -14317,12 +13389,12 @@ var ts; var dotdotdot = parseOptionalToken(24); var type = parseType(); if (dotdotdot) { - var variadic = createNode(282, dotdotdot.pos); + var variadic = createNode(284, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } if (token() === 58) { - return createJSDocPostfixType(280, type); + return createJSDocPostfixType(282, type); } return type; } @@ -14390,10 +13462,11 @@ var ts; signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - signature.type = parseReturnType(returnToken, !!(flags & 4)); - } - function parseReturnType(returnToken, isType) { - return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + if (shouldParseReturnType(returnToken, !!(flags & 4))) { + signature.type = parseTypeOrTypePredicate(); + return signature.type !== undefined; + } + return true; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36) { @@ -14615,6 +13688,9 @@ var ts; var node = createNode(172); parseExpected(19); node.type = parseType(); + if (!node.type) { + return undefined; + } parseExpected(20); return finishNode(node); } @@ -14623,7 +13699,12 @@ var ts; if (kind === 163) { parseExpected(94); } - fillSignature(36, 4, node); + if (!fillSignature(36, 4 | (sourceFile.languageVariant === 1 ? 8 : 0), node)) { + return undefined; + } + if (!node.parameters) { + return undefined; + } return finishNode(node); } function parseKeywordAndNoDot() { @@ -14776,13 +13857,13 @@ var ts; while (!scanner.hasPrecedingLineBreak()) { switch (token()) { case 51: - type = createJSDocPostfixType(279, type); + type = createJSDocPostfixType(281, type); break; case 55: if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createJSDocPostfixType(278, type); + type = createJSDocPostfixType(280, type); break; case 21: parseExpected(21); @@ -15223,7 +14304,9 @@ var ts; var node = createNodeWithJSDoc(192); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); + if (!fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node)) { + return undefined; + } if (!node.parameters) { return undefined; } @@ -17109,39 +16192,6 @@ var ts; function isImportMeta(node) { return ts.isMetaProperty(node) && node.keywordToken === 91 && node.name.escapedText === "meta"; } - var ParsingContext; - (function (ParsingContext) { - ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; - ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; - ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; - ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; - ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; - ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; - ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; - ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; - ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; - ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; - ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; - ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; - ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; - ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; - ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; - ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; - ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; - ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; - })(ParsingContext || (ParsingContext = {})); - var Tristate; - (function (Tristate) { - Tristate[Tristate["False"] = 0] = "False"; - Tristate[Tristate["True"] = 1] = "True"; - Tristate[Tristate["Unknown"] = 2] = "Unknown"; - })(Tristate || (Tristate = {})); var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { @@ -17156,7 +16206,7 @@ var ts; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(275, scanner.getTokenPos()); + var result = createNode(277, scanner.getTokenPos()); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17); result.type = doInsideOfContext(2097152, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -17176,6 +16226,7 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var _a; var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -17193,20 +16244,8 @@ var ts; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; - var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; - var JSDocState; - (function (JSDocState) { - JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; - JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; - JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; - })(JSDocState || (JSDocState = {})); - var PropertyLikeParse; - (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; - })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -17248,7 +16287,7 @@ var ts; case 57: if (state === 0 || state === 1) { removeTrailingNewlines(comments); - parseTag(indent); + addTag(parseTag(indent)); state = 0; margin = undefined; indent++; @@ -17312,12 +16351,28 @@ var ts; } } function createJSDocComment() { - var result = createNode(283, start); + var result = createNode(285, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } + function isNextNonwhitespaceTokenEndOfFile() { + while (true) { + nextJSDocToken(); + if (token() === 1) { + return true; + } + if (!(token() === 5 || token() === 4)) { + return false; + } + } + } function skipWhitespace() { + if (token() === 5 || token() === 4) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; + } + } while (token() === 5 || token() === 4) { nextJSDocToken(); } @@ -17346,8 +16401,7 @@ var ts; case "arg": case "argument": case "param": - addTag(parseParameterOrPropertyTag(atToken, tagName, 1, indent)); - return; + return parseParameterOrPropertyTag(atToken, tagName, 2, indent); case "return": case "returns": tag = parseReturnTag(atToken, tagName); @@ -17359,7 +16413,10 @@ var ts; tag = parseTypeTag(atToken, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(atToken, tagName, indent); break; default: tag = parseUnknownTag(atToken, tagName); @@ -17372,8 +16429,10 @@ var ts; if (!tag) { return; } - tag.comment = parseTagComments(indent + tag.end - tag.pos); - addTag(tag); + if (!tag.comment) { + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; } function parseTagComments(indent) { var comments = []; @@ -17430,12 +16489,15 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { - var result = createNode(285, atToken.pos); + var result = createNode(288, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } function addTag(tag) { + if (!tag) { + return; + } if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -17484,8 +16546,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 ? - createNode(288, atToken.pos) : - createNode(293, atToken.pos); + createNode(297, atToken.pos) : + createNode(292, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -17505,18 +16567,18 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name, target) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(275, scanner.getTokenPos()); + var typeLiteralExpression = createNode(277, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 288 || child.kind === 293) { + if (child.kind === 292 || child.kind === 297) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(284, start_2); + jsdocTypeLiteral = createNode(286, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; if (typeExpression.type.kind === 166) { jsdocTypeLiteral.isArrayType = true; @@ -17527,27 +16589,27 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289; })) { + if (ts.forEach(tags, function (t) { return t.kind === 293; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(289, atToken.pos); + var result = createNode(293, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 290; })) { + if (ts.forEach(tags, function (t) { return t.kind === 294; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(290, atToken.pos); + var result = createNode(294, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var result = createNode(286, atToken.pos); + var result = createNode(289, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); @@ -17575,30 +16637,23 @@ var ts; return node; } function parseClassTag(atToken, tagName) { - var tag = createNode(287, atToken.pos); + var tag = createNode(290, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); } - function parseTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(292, atToken.pos); + var typedefTag = createNode(296, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 || !rightNode.body) { - typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); skipWhitespace(); + typedefTag.comment = parseTagComments(indent); typedefTag.typeExpression = typeExpression; + var end; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; @@ -17606,9 +16661,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(284, start_3); + jsdocTypeLiteral = createNode(286, start_3); } - if (child.kind === 290) { + if (child.kind === 294) { if (childTypeTag) { break; } @@ -17627,23 +16682,67 @@ var ts; typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; } } - return finishNode(typedefTag); - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(238, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); - return finishNode(jsDocNamespaceNode); + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23)) { + var jsDocNamespaceNode = createNode(238, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4; } - if (typeNameOrNamespaceName && flags & 4) { - typeNameOrNamespaceName.isInJSDocNamespace = true; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(true); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(atToken, tagName, indent) { + var callbackTag = createNode(291, atToken.pos); + callbackTag.atToken = atToken; + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var start = scanner.getStartPos(); + var jsdocSignature = createNode(287, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (token() === 57) { + nextJSDocToken(); + var tag = parseTag(indent); + if (tag && tag.kind === 293) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; } - return typeNameOrNamespaceName; } } function escapedTextsEqual(a, b) { @@ -17659,7 +16758,7 @@ var ts; return a.escapedText === b.escapedText; } function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(0); + return parseChildParameterOrPropertyTag(1); } function parseChildParameterOrPropertyTag(target, name) { var canParseTag = true; @@ -17669,7 +16768,8 @@ var ts; case 57: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 288 && + if (child && child.kind === 292 && + target !== 4 && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -17708,20 +16808,20 @@ var ts; var t; switch (tagName.escapedText) { case "type": - return target === 0 && parseTypeTag(atToken, tagName); + return target === 1 && parseTypeTag(atToken, tagName); case "prop": case "property": - t = 0; + t = 1; break; case "arg": case "argument": case "param": - t = 1; + t = 2 | 4; break; default: return false; } - if (target !== t) { + if (!(target & t)) { return false; } var tag = parseParameterOrPropertyTag(atToken, tagName, target, undefined); @@ -17753,7 +16853,7 @@ var ts; break; } } - var result = createNode(291, atToken.pos); + var result = createNode(295, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -17799,7 +16899,7 @@ var ts; var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); var result = createNode(71, pos); - result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); return result; @@ -18095,10 +17195,6 @@ var ts; } } } - var InvalidPosition; - (function (InvalidPosition) { - InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; - })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); @@ -18302,12 +17398,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ModuleInstanceState; - (function (ModuleInstanceState) { - ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; - ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; - ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; - })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { return node.body ? getModuleInstanceStateWorker(node.body) : 1; } @@ -18356,18 +17446,6 @@ var ts; } return 1; } - var ContainerFlags; - (function (ContainerFlags) { - ContainerFlags[ContainerFlags["None"] = 0] = "None"; - ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; - ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; - ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; - ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; - ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; - ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; - ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; - ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; - })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -18385,7 +17463,7 @@ var ts; var thisParentContainer; var blockScopeContainer; var lastContainer; - var delayedTypedefs; + var delayedTypeAliases; var seenThisKeyword; var currentFlow; var currentBreakTarget; @@ -18431,7 +17509,7 @@ var ts; thisParentContainer = undefined; blockScopeContainer = undefined; lastContainer = undefined; - delayedTypedefs = undefined; + delayedTypeAliases = undefined; seenThisKeyword = false; currentFlow = undefined; currentBreakTarget = undefined; @@ -18500,6 +17578,7 @@ var ts; return "__constructor"; case 162: case 157: + case 287: return "__call"; case 163: case 158: @@ -18508,22 +17587,21 @@ var ts; return "__index"; case 249: return "__export"; + case 273: + return "export="; case 199: if (ts.getSpecialPropertyAssignmentKind(node) === 2) { return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 281: + case 283: return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); case 148: - ts.Debug.assert(node.parent.kind === 281, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 283, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; - case 292: - var name_2 = ts.getNameOfJSDocTypedef(node); - return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } } function getDisplayName(node) { @@ -18603,9 +17681,9 @@ var ts; } } else { - if (node.kind === 292) + if (ts.isJSDocTypeAlias(node)) ts.Debug.assert(ts.isInJavaScriptFile(node)); - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || ts.isJSDocTypedefTag(node)) { + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } @@ -18742,20 +17820,6 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var j = _a[_i]; - bind(j); - } - } - else { - for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { - var j = _c[_b]; - setParentPointers(node, j); - } - } - } if (checkUnreachable(node)) { bindEachChild(node); return; @@ -18821,11 +17885,9 @@ var ts; case 186: bindCallExpressionFlow(node); break; - case 283: - bindJSDocComment(node); - break; - case 292: - bindJSDocTypedefTag(node); + case 296: + case 291: + bindJSDocTypeAlias(node); break; case 273: bindEachFunctionsFirst(node.statements); @@ -18839,6 +17901,7 @@ var ts; bindEachChild(node); break; } + bindJSDoc(node); } function isNarrowingExpression(expr) { switch (expr.kind) { @@ -19401,20 +18464,10 @@ var ts; bindInitializedVariableFlow(node); } } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 292) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - if (node.fullName && n === node.name && node.fullName.kind !== 71) { - return; - } - bind(n); - }); + function bindJSDocTypeAlias(node) { + if (node.fullName) { + setParentPointers(node, node.fullName); + } } function bindCallExpressionFlow(node) { var expr = node.expression; @@ -19443,7 +18496,7 @@ var ts; case 237: case 183: case 165: - case 284: + case 286: case 262: return 1; case 235: @@ -19464,7 +18517,8 @@ var ts; case 155: case 156: case 157: - case 281: + case 287: + case 283: case 162: case 158: case 159: @@ -19506,7 +18560,7 @@ var ts; case 237: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 165: - case 284: + case 286: case 183: case 235: case 262: @@ -19515,6 +18569,7 @@ var ts; case 163: case 157: case 158: + case 287: case 159: case 153: case 152: @@ -19524,7 +18579,9 @@ var ts; case 233: case 191: case 192: - case 281: + case 283: + case 296: + case 291: case 236: case 176: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); @@ -19609,11 +18666,6 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node) { - var ElementKind; - (function (ElementKind) { - ElementKind[ElementKind["Property"] = 1] = "Property"; - ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; - })(ElementKind || (ElementKind = {})); if (inStrictMode) { var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { @@ -19673,22 +18725,35 @@ var ts; bindBlockScopedDeclaration(node, 2, 67216319); } function delayedBindJSDocTypedefTag() { - if (!delayedTypedefs) { + if (!delayedTypeAliases) { return; } var saveContainer = container; var saveLastContainer = lastContainer; var saveBlockScopeContainer = blockScopeContainer; var saveParent = parent; - for (var _i = 0, delayedTypedefs_1 = delayedTypedefs; _i < delayedTypedefs_1.length; _i++) { - var delay = delayedTypedefs_1[_i]; - (container = delay.container, lastContainer = delay.lastContainer, blockScopeContainer = delay.blockScopeContainer, parent = delay.parent); - bindBlockScopedDeclaration(delay.typedef, 524288, 67901928); + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 71) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288, 67901928); + } + else { + bind(typeAlias.fullName); + } } container = saveContainer; lastContainer = saveLastContainer; blockScopeContainer = saveBlockScopeContainer; parent = saveParent; + currentFlow = saveCurrentFlow; } function checkStrictModeIdentifier(node) { if (inStrictMode && @@ -19803,8 +18868,6 @@ var ts; } node.parent = parent; var saveInStrictMode = inStrictMode; - if (ts.isInJavaScriptFile(node)) - bindJSDocTypedefTagIfAny(node); bindWorker(node); if (node.kind > 144) { var saveParent = parent; @@ -19820,25 +18883,22 @@ var ts; } else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + bindJSDoc(node); } inStrictMode = saveInStrictMode; } - function bindJSDocTypedefTagIfAny(node) { - if (!ts.hasJSDocNodes(node)) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 292) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); } } } @@ -19866,7 +18926,7 @@ var ts; case 71: if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 292) { + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } bindBlockScopedDeclaration(parentNode, 524288, 67901928); @@ -19962,11 +19022,12 @@ var ts; case 156: return bindPropertyOrMethodOrAccessor(node, 65536, 67183551); case 162: - case 281: + case 283: + case 287: case 163: return bindFunctionOrConstructorType(node); case 165: - case 284: + case 286: case 176: return bindAnonymousTypeWorker(node); case 183: @@ -20017,23 +19078,22 @@ var ts; } case 239: return updateStrictModeStatementList(node.statements); - case 288: - if (node.parent.kind !== 284) { + case 292: + if (node.parent.kind === 287) { + return bindParameter(node); + } + if (node.parent.kind !== 286) { break; } - case 293: + case 297: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 280 ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 282 ? 4 | 16777216 : 4; return declareSymbolAndAddToSymbolTable(propTag, flags, 0); - case 292: { - var fullName = node.fullName; - if (!fullName || fullName.kind === 71) { - (delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node, container: container, lastContainer: lastContainer, blockScopeContainer: blockScopeContainer, parent: parent }); - } - break; - } + case 296: + case 291: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } function bindPropertyWorker(node) { @@ -20047,6 +19107,12 @@ var ts; if (ts.isExternalModule(file)) { bindSourceFileAsExternalModule(); } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4, 67108863); + file.symbol = originalSymbol; + } } function bindSourceFileAsExternalModule() { bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); @@ -20323,6 +19389,9 @@ var ts; } } function bindParameter(node) { + if (node.kind === 292 && container.kind !== 287) { + return; + } if (inStrictMode && !(node.flags & 4194304)) { checkStrictModeEvalOrArguments(node, node.name); } @@ -20377,24 +19446,30 @@ var ts; : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } function getInferTypeContainer(node) { - while (node) { - var parent_2 = node.parent; - if (parent_2 && parent_2.kind === 170 && parent_2.extendsType === node) { - return parent_2; - } - node = parent_2; - } - return undefined; + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; } function bindTypeParameter(node) { - if (node.parent.kind === 171) { - var container_1 = getInferTypeContainer(node.parent); + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); if (container_1) { if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } declareSymbol(container_1.locals, undefined, node, 262144, 67639784); } + else { + declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + } + } + else if (node.parent.kind === 171) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, undefined, node, 262144, 67639784); + } else { bindAnonymousDeclaration(node, 262144, getDeclarationName(node)); } @@ -20718,7 +19793,7 @@ var ts; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; - if (node.initializer) { + if (node.initializer || ts.isComputedPropertyName(node.name)) { transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; @@ -20897,7 +19972,7 @@ var ts; break; case 189: case 207: - case 296: + case 300: transformFlags |= 3; excludeFlags = 536872257; break; @@ -21130,7 +20205,7 @@ var ts; return 940049729; case 189: case 207: - case 296: + case 300: case 190: case 97: return 536872257; @@ -21144,7 +20219,7 @@ var ts; ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; function setParentPointers(parent, child) { child.parent = parent; - ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); } })(ts || (ts = {})); var ts; @@ -21328,7 +20403,8 @@ var ts; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; })(Extensions || (Extensions = {})); function resolvedTypeScriptOnly(resolved) { if (!resolved) { @@ -21369,7 +20445,13 @@ var ts; function readJson(path, host) { try { var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; } catch (e) { return {}; @@ -21779,7 +20861,11 @@ var ts; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + var result = jsOnly ? + tryResolve(Extensions.JavaScript) : + (tryResolve(Extensions.TypeScript) || + tryResolve(Extensions.JavaScript) || + (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); @@ -21832,7 +20918,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); if (!directoryProbablyExists(parentOfCandidate, state.host)) { @@ -21900,6 +20986,10 @@ var ts; return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); } function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (extensions === Extensions.Json) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json"); + return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + } var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; @@ -21915,9 +21005,9 @@ var ts; } function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + var directory_1 = ts.getDirectoryPath(candidate); + if (directory_1) { + onlyRecordFailures = !directoryProbablyExists(directory_1, state.host); } } switch (extensions) { @@ -21927,6 +21017,8 @@ var ts; return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); case Extensions.JavaScript: return tryExtension(".js") || tryExtension(".jsx"); + case Extensions.Json: + return tryExtension(".json"); } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); @@ -21978,8 +21070,11 @@ var ts; } else { var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string") { - subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js"), ".jsx") + ".d.ts"; + if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { + var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts"; } else { subModuleName = "index.d.ts"; @@ -22011,9 +21106,17 @@ var ts; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); if (!file) { - return undefined; + if (extensions === Extensions.TypeScript) { + file = tryReadPackageJsonFields(false, jsonContent, candidate, state); + if (!file) { + return undefined; + } + } + else { + return undefined; + } } var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); @@ -22041,6 +21144,8 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" || extension === ".jsx"; + case Extensions.Json: + return extension === ".json"; case Extensions.TypeScript: return extension === ".ts" || extension === ".tsx" || extension === ".d.ts"; case Extensions.DtsOnly: @@ -22106,7 +21211,7 @@ var ts; if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript) { + if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { @@ -22493,7 +21598,7 @@ var ts; checkSourceFile(file); var diagnostics = []; ts.Debug.assert(!!(getNodeLinks(file).flags & 1)); - checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { if (!unusedIsError(kind)) { diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } @@ -22561,6 +21666,7 @@ var ts; var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); + var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); var globals = ts.createSymbolTable(); @@ -22597,8 +21703,6 @@ var ts; var deferredGlobalExtractSymbol; var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); - var potentiallyUnusedIdentifiers; - var seenPotentiallyUnusedIdentifiers = ts.createMap(); var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -22624,65 +21728,6 @@ var ts; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createMultiMap(); - var TypeFacts; - (function (TypeFacts) { - TypeFacts[TypeFacts["None"] = 0] = "None"; - TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; - TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; - TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean"; - TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol"; - TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject"; - TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction"; - TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject"; - TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString"; - TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber"; - TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean"; - TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol"; - TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject"; - TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction"; - TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject"; - TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined"; - TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull"; - TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull"; - TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined"; - TypeFacts[TypeFacts["NENull"] = 262144] = "NENull"; - TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; - TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; - TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["All"] = 4194303] = "All"; - TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; - TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; - TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; - TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; - TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; - TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; - TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; - TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; - TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; - TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; - TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; - TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; - TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; - TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; - TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; - TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; - TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; - TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; - TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; - TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; - TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; - TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; - TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; - TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; - TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; - TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; - })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1, number: 2, @@ -22717,51 +21762,6 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - var TypeSystemPropertyName; - (function (TypeSystemPropertyName) { - TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; - TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; - })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); - var CheckMode; - (function (CheckMode) { - CheckMode[CheckMode["Normal"] = 0] = "Normal"; - CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; - CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; - CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; - })(CheckMode || (CheckMode = {})); - var CallbackCheck; - (function (CallbackCheck) { - CallbackCheck[CallbackCheck["None"] = 0] = "None"; - CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; - CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; - })(CallbackCheck || (CallbackCheck = {})); - var MappedTypeModifiers; - (function (MappedTypeModifiers) { - MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly"; - MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly"; - MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional"; - MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional"; - })(MappedTypeModifiers || (MappedTypeModifiers = {})); - var ExpandingFlags; - (function (ExpandingFlags) { - ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; - ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; - ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; - ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; - })(ExpandingFlags || (ExpandingFlags = {})); - var MembersOrExportsResolutionKind; - (function (MembersOrExportsResolutionKind) { - MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; - MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; - })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); - var UnusedKind; - (function (UnusedKind) { - UnusedKind[UnusedKind["Local"] = 0] = "Local"; - UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter"; - })(UnusedKind || (UnusedKind = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -22902,17 +21902,17 @@ var ts; } function getJsxNamespace(location) { if (location) { - var file = ts.getSourceFileOfNode(location); - if (file) { - if (file.localJsxNamespace) { - return file.localJsxNamespace; + var file_1 = ts.getSourceFileOfNode(location); + if (file_1) { + if (file_1.localJsxNamespace) { + return file_1.localJsxNamespace; } - var jsxPragma = file.pragmas.get("jsx"); + var jsxPragma = file_1.pragmas.get("jsx"); if (jsxPragma) { var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; - file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); - if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file_1.localJsxFactory) { + return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText; } } } @@ -23022,6 +22022,8 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864) { + var targetValueDeclaration = target.valueDeclaration; + ts.Debug.assert(!!(target.flags & 33554432)); if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; } @@ -23044,7 +22046,12 @@ var ts; } if ((source.flags | target.flags) & 67108864) { var sourceInitializer = ts.getJSInitializerSymbol(source); - var targetInitializer = ts.getJSInitializerSymbol(target); + var init = ts.getDeclaredJavascriptInitializer(targetValueDeclaration) || ts.getAssignedJavascriptInitializer(targetValueDeclaration); + var targetInitializer = init && init.symbol ? init.symbol : target; + if (!(targetInitializer.flags & 33554432)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } if (sourceInitializer !== source || targetInitializer !== target) { mergeSymbol(targetInitializer, sourceInitializer); } @@ -23275,7 +22282,7 @@ var ts; if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 67901928 && lastLocation.kind !== 283) { + if (meaning & result.flags & 67901928 && lastLocation.kind !== 285) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 148 || @@ -23417,6 +22424,11 @@ var ts; location = location.parent; } break; + case 296: + case 291: + lastLocation = location; + location = ts.getJSDocHost(location).parent; + continue; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -23514,9 +22526,11 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (decl.kind === 147 && parent === container) { - return true; + if (decl.kind === 147) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + } } } return false; @@ -23703,8 +22717,8 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default", dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); - var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + var file_2 = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file_2, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -23911,7 +22925,7 @@ var ts; var symbol; if (name.kind === 71) { var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSPrototype(name, meaning) : undefined; + var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); if (!symbol) { return symbolFromJSPrototype; @@ -23920,39 +22934,39 @@ var ts; else if (name.kind === 145 || name.kind === 184) { var left = name.kind === 145 ? name.left : name.expression; var right = name.kind === 145 ? name.right : name.name; - var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, false, location); - if (!namespace || ts.nodeIsMissing(right)) { + var namespace_1 = resolveEntityName(left, namespaceMeaning, ignoreErrors, false, location); + if (!namespace_1 || ts.nodeIsMissing(right)) { return undefined; } - else if (namespace === unknownSymbol) { - return namespace; + else if (namespace_1 === unknownSymbol) { + return namespace_1; } if (ts.isInJavaScriptFile(name)) { - var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); + var initializer = ts.getDeclaredJavascriptInitializer(namespace_1.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace_1.valueDeclaration); if (initializer) { - namespace = getSymbolOfNode(initializer); + namespace_1 = getSymbolOfNode(initializer); } - if (!namespace) { + if (!namespace_1) { return undefined; } - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + if (namespace_1.valueDeclaration && + ts.isVariableDeclaration(namespace_1.valueDeclaration) && + namespace_1.valueDeclaration.initializer && + isCommonJsRequire(namespace_1.valueDeclaration.initializer)) { + var moduleName = namespace_1.valueDeclaration.initializer.arguments[0]; var moduleSym = resolveExternalModuleName(moduleName, moduleName); if (moduleSym) { var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; + namespace_1 = resolvedModuleSymbol; } } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getSymbol(getExportsOfSymbol(namespace_1), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace_1), ts.declarationNameToString(right)); } return undefined; } @@ -23963,20 +22977,32 @@ var ts; ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } - function resolveEntityNameFromJSPrototype(name, meaning) { - if (isJSDocTypeReference(name.parent) && ts.isJSDocTag(name.parent.parent.parent)) { - var host_1 = ts.getJSDocHost(name.parent.parent.parent); - if (ts.isExpressionStatement(host_1) && - ts.isBinaryExpression(host_1.expression) && - ts.getSpecialPropertyAssignmentKind(host_1.expression) === 3) { - var symbol = getSymbolOfNode(host_1.expression.left); - if (symbol) { - var secondaryLocation = symbol.parent.valueDeclaration; - return resolveName(secondaryLocation, name.escapedText, meaning, undefined, name, true); - } + function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, undefined, name, true); } } } + function getJSSpecialAssignmentLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getSpecialPropertyAssignmentKind(host.expression) === 3) { + var symbol = getSymbolOfNode(host.expression.left); + return symbol && symbol.parent.valueDeclaration; + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -24022,7 +23048,7 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -24033,6 +23059,21 @@ var ts; return undefined; } if (moduleNotFoundError) { + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts", ".tsx"]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } if (resolutionDiagnostic) { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } @@ -24429,7 +23470,7 @@ var ts; return access.accessibility === 0; } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { + if (symbol && enclosingDeclaration) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { @@ -24445,6 +23486,13 @@ var ts; } return hasAccessibleDeclarations; } + else { + if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + return { + accessibility: 0 + }; + } + } meaningToLook = getQualifiedLeftMeaning(meaning); symbol = getParentOfSymbol(symbol); } @@ -24492,6 +23540,11 @@ var ts; isDeclarationVisible(declaration.parent.parent.parent)) { return addVisibleAlias(declaration, declaration.parent.parent); } + else if (ts.isLateVisibilityPaintedStatement(declaration) + && !ts.hasModifier(declaration, 1) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } return false; } return true; @@ -24649,7 +23702,7 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined, + visitedSymbols: undefined, inferTypeParameters: undefined }; } @@ -24741,15 +23794,24 @@ var ts; } if (type.flags & 32768 || objectFlags & 3) { if (type.flags & 32768 && ts.contains(context.inferTypeParameters, type)) { - return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, undefined)); + } + if (context.flags & 4 && + type.flags & 32768 && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8), undefined); } var name = type.symbol ? symbolToName(type.symbol, context, 67901928, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { - var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name, typeArgumentNodes); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67901928, typeArgumentNodes); } if (type.flags & (131072 | 262144)) { var types = type.flags & 131072 ? formatUnionTypes(type.types) : type.types; @@ -24797,14 +23859,24 @@ var ts; ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; + var id; if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); if (isJavaScriptConstructor(symbol.valueDeclaration)) { var isInstanceType = type === getInferredClassType(symbol) ? 67901928 : 67216319; return symbolToTypeNode(symbol, context, isInstanceType); @@ -24814,7 +23886,7 @@ var ts; shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, 67216319); } - else if (ts.contains(context.symbolStack, symbol)) { + else if (context.visitedSymbols && context.visitedSymbols.has(id)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { return symbolToTypeNode(typeAlias, context, 67901928); @@ -24824,19 +23896,13 @@ var ts; } } else { - if (!context.symbolStack) { - context.symbolStack = []; - } - var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; - if (isConstructorObject) { - return createTypeNodeFromObjectType(type); - } - else { - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + if (!context.visitedSymbols) { + context.visitedSymbols = ts.createMap(); } + context.visitedSymbols.set(id, true); + var result = createTypeNodeFromObjectType(type); + context.visitedSymbols.delete(id); + return result; } } else { @@ -24851,7 +23917,7 @@ var ts; return declaration.parent.kind === 273 || declaration.parent.kind === 239; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return (!!(context.flags & 4096) || ts.contains(context.symbolStack, symbol)) && + return (!!(context.flags & 4096) || (context.visitedSymbols && context.visitedSymbols.has(id))) && (!(context.flags & 8) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); } } @@ -24883,10 +23949,6 @@ var ts; var typeLiteralNode = ts.createTypeLiteralNode(members); return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024) ? 0 : 1); } - function symbolToTypeReferenceName(symbol) { - var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928, false) : ts.createIdentifier(""); - return entityName; - } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { @@ -24919,7 +23981,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = void 0; + var resultType = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -24930,55 +23992,61 @@ var ts; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); - var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); - var namePart = symbolToTypeReferenceName(parent); - (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); - } - else { - qualifiedName = ts.createQualifiedName(namePart, undefined); - } + var flags_2 = context.flags; + context.flags |= 16; + var ref = symbolToTypeNode(parent, context, 67901928, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } } } - var entityName = void 0; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } var typeArgumentNodes = void 0; if (typeArguments.length > 0) { var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } - if (typeArgumentNodes) { - var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; - lastIdentifier.typeArguments = undefined; - } - return ts.createTypeReferenceNode(entityName, typeArgumentNodes); + var flags = context.flags; + context.flags |= 16; + var finalRef = symbolToTypeNode(type.symbol, context, 67901928, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } } - function addToQualifiedNameMissingRightIdentifier(left, right) { - ts.Debug.assert(left.right === undefined); - if (right.kind === 71) { - left.right = right; - return left; + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; } - var rightPart = right; - while (rightPart.left.kind !== 71) { - rightPart = rightPart.left; + else { + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; } - left.right = rightPart.left; - rightPart.left = left; - return right; + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; @@ -25116,32 +24184,47 @@ var ts; } return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928, undefined, type.symbol.escapedName, false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; context.flags &= ~512; - var name = symbolToName(type.symbol, context, 67901928, true); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var shouldUseGeneratedName = context.flags & 4 && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8) + : symbolToName(type.symbol, context, 67901928, true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148); - ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 292); + } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; + var dotDotDotToken = isRest ? ts.createToken(24) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : - cloneBindingName(parameterDeclaration.name) : + parameterDeclaration.name.kind === 71 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + parameterDeclaration.name.kind === 145 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216) : + cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; @@ -25159,7 +24242,7 @@ var ts; } } } - function lookupSymbolChain(symbol, context, meaning) { + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; var isTypeParameter = symbol.flags & 262144; @@ -25189,7 +24272,7 @@ var ts; return accessibleSymbolChain; } if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && !(symbol.flags & (2048 | 4096))) { return [symbol]; } @@ -25220,21 +24303,50 @@ var ts; } return typeParameterNodes; } - function symbolToTypeNode(symbol, context, meaning) { - var chain = lookupSymbolChain(symbol, context, meaning); + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384)); context.flags |= 16777216; var rootName = getNameOfSymbolAsWritten(chain[0], context); context.flags ^= 16777216; var isTypeOf = meaning === 67216319; if (ambientModuleSymbolRegex.test(rootName)) { - var nonRootParts = chain.length > 1 ? createEntityNameFromSymbolChain(chain, chain.length - 1, 1) : undefined; - var typeParameterNodes = lookupTypeParameterNodes(chain, 0, context); - return ts.createImportTypeNode(ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))), nonRootParts, typeParameterNodes, isTypeOf); + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))); + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } } - var entityName = createEntityNameFromSymbolChain(chain, chain.length - 1, 0); - return isTypeOf ? ts.createTypeQueryNode(entityName) : ts.createTypeReferenceNode(entityName, undefined); - function createEntityNameFromSymbolChain(chain, index, stopper) { - var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; if (index === 0) { context.flags |= 16777216; @@ -25243,9 +24355,26 @@ var ts; if (index === 0) { context.flags ^= 16777216; } + var parent = chain[index - 1]; + if (!(context.flags & 16) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); identifier.symbol = symbol; - return index > stopper ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1, stopper), identifier) : identifier; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; } } function symbolToName(symbol, context, meaning, expectsIdentifier) { @@ -25384,6 +24513,23 @@ var ts; return "default"; } if (symbol.declarations && symbol.declarations.length) { + if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { + var file_3 = ts.getDeclarationOfKind(symbol, 273); + if (!file_3 || !context.tracker.moduleResolverHost) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl); + } + } + } + } + else { + return "\"" + ts.getResolvedExternalModuleName(context.tracker.moduleResolverHost, file_3, ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration))) + "\""; + } + } var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { @@ -25425,6 +24571,9 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { + case 291: + case 296: + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); case 181: return isDeclarationVisible(node.parent.parent); case 231: @@ -26038,6 +25187,10 @@ var ts; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } if (declaration.kind === 248) { return links.type = checkExpression(declaration.expression); } @@ -26052,7 +25205,7 @@ var ts; declaration.kind === 184 && declaration.parent.kind === 199) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else if (ts.isJSDocPropertyTag(declaration) + else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) || ts.isIdentifier(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) @@ -26307,12 +25460,14 @@ var ts; case 152: case 162: case 163: - case 281: + case 283: case 233: case 153: case 191: case 192: case 236: + case 295: + case 296: case 291: case 176: case 170: @@ -26323,7 +25478,7 @@ var ts; else if (node.kind === 170) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 234 || node.kind === 204 || node.kind === 235) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; @@ -26339,13 +25494,12 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 235 || node.kind === 234 || - node.kind === 204 || node.kind === 236) { + if (node.kind === 235 || + node.kind === 234 || + node.kind === 204 || + ts.isTypeAlias(node)) { var declaration = node; - var typeParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - if (typeParameters) { - result = appendTypeParameters(result, typeParameters); - } + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); } } return result; @@ -26579,9 +25733,9 @@ var ts; return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 292 || d.kind === 236; + return ts.isJSDocTypeAlias(d) || d.kind === 236; }); - var typeNode = declaration.kind === 292 ? declaration.typeExpression : declaration.type; + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -26768,7 +25922,7 @@ var ts; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); return (node.kind === 154 || (returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && - (!typeParameters || typeParameters.every(isThislessTypeParameter)); + typeParameters.every(isThislessTypeParameter); } function isThisless(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { @@ -26808,6 +25962,8 @@ var ts; var symbol = type.symbol; var members = getMembersOfSymbol(symbol); type.declaredProperties = getNamedMembers(members); + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call")); type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new")); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); @@ -26873,9 +26029,9 @@ var ts; var earlySymbol = earlySymbols && earlySymbols.get(memberName); if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_3 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); lateSymbol = createSymbol(0, memberName, 1024); } lateSymbol.nameType = type; @@ -27256,10 +26412,8 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); var templateModifiers = getMappedTypeModifiers(type); - var constraintDeclaration = type.declaration.typeParameter.constraint; var include = keyofStringsOnly ? 32 : 1120; - if (constraintDeclaration.kind === 174 && - constraintDeclaration.operator === 128) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), undefined, prop); @@ -27320,12 +26474,18 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4)), type.mapper || identityMapper) : unknownType); } + function getConstraintDeclarationForMappedType(type) { + return type.declaration.typeParameter.constraint; + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); + return constraintDeclaration.kind === 174 && + constraintDeclaration.operator === 128; + } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 174 && - constraintDeclaration.operator === 128) { - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); } else { var declaredType = getTypeFromMappedTypeNode(type.declaration); @@ -27471,9 +26631,9 @@ var ts; } function getConstraintOfDistributiveConditionalType(type) { if (type.root.isDistributive) { - var constraint = getConstraintOfType(type.checkType); + var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); if (constraint) { - var mapper = createTypeMapper([type.root.checkType], [constraint]); + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 16384)) { return instantiated; @@ -27800,9 +26960,10 @@ var ts; } function getTypeParametersFromDeclaration(declaration) { var result; - ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); - }); + } return result; } function symbolsToArray(symbols) { @@ -27815,10 +26976,10 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 280 + return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 282 || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 280; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -27829,7 +26990,7 @@ var ts; return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -27846,6 +27007,13 @@ var ts; } return false; } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282; + } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); @@ -27887,7 +27055,7 @@ var ts; for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); @@ -27915,6 +27083,7 @@ var ts; for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319, undefined, undefined, false); paramSymbol = resolvedSymbol; @@ -27926,11 +27095,12 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 177) { + if (type && type.kind === 177) { hasLiteralTypes = true; } - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || isUntypedSignatureInJSFile || isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { @@ -27957,7 +27127,7 @@ var ts; return links.resolvedSignature; } function maybeAddJsSyntheticRestParameter(declaration, parameters) { - if (!containsArgumentsReference(declaration)) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { return false; } var lastParam = ts.lastOrUndefined(declaration.parameters); @@ -28316,7 +27486,7 @@ var ts; var isJs = ts.isInJavaScriptFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 286; + var missingAugmentsTag = isJs && node.parent.kind !== 289; var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -28448,7 +27618,7 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node)) { + while (node && !ts.isStatement(node) && node.kind !== 285) { var parent = node.parent; if (parent.kind === 170 && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); @@ -28860,7 +28030,7 @@ var ts; includes & 4096 ? includes & 16777216 ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 8374815 ? 0 : 268435456, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -28894,7 +28064,7 @@ var ts; ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex : !ts.isIdentifierTypePredicate(b); } - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -28905,7 +28075,7 @@ var ts; var type = unionTypes.get(id); if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, 12288); - type = createType(131072 | propagatedFlags); + type = createType(131072 | propagatedFlags | unionOfUnitTypes); unionTypes.set(id, type); type.types = types; type.aliasSymbol = aliasSymbol; @@ -28916,7 +28086,8 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -28963,6 +28134,28 @@ var ts; } } } + function intersectUnionsOfUnitTypes(types) { + var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 268435456) !== 0; }); + var unionType = types[unionIndex]; + var intersection = unionType.types; + var i = types.length - 1; + var _loop_5 = function () { + var t = types[i]; + if (t.flags & 268435456) { + intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + ts.orderedRemoveItemAt(types, i); + } + i--; + }; + while (i > unionIndex) { + _loop_5(); + } + if (intersection === unionType.types) { + return false; + } + types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 268435456); + return true; + } function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return emptyObjectType; @@ -28987,6 +28180,9 @@ var ts; return typeSet[0]; } if (includes & 131072) { + if (includes & 268435456 && intersectUnionsOfUnitTypes(typeSet)) { + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 131072) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1, aliasSymbol, aliasTypeArguments); @@ -29006,7 +28202,8 @@ var ts; function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -29179,6 +28376,10 @@ var ts; return type.flags & 1048576 ? getSimplifiedIndexedAccessType(type) : type; } function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; var objectType = type.objectType; if (objectType.flags & 262144 && isGenericObjectType(objectType)) { if (ts.some(objectType.types, isStringIndexOnlyType)) { @@ -29193,26 +28394,26 @@ var ts; regularTypes.push(t); } } - return getUnionType([ + return type.simplified = getUnionType([ getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), getIntersectionType(stringIndexTypes) ]); } if (ts.some(objectType.types, isMappedTypeToNever)) { var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); } } if (isGenericMappedType(objectType)) { - return substituteIndexedMappedType(objectType, type); + return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 32768) { var constraint = getConstraintFromTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { - return substituteIndexedMappedType(constraint, type); + return type.simplified = substituteIndexedMappedType(constraint, type); } } - return type; + return type.simplified = type; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); @@ -29268,7 +28469,7 @@ var ts; var type = createObjectType(32, node.symbol); type.declaration = node; type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); links.resolvedType = type; getConstraintTypeFromMappedType(type); } @@ -29286,11 +28487,11 @@ var ts; var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088); var combinedMapper; if (root.inferTypeParameters) { - var context = createInferenceContext(root.inferTypeParameters, undefined, 0); + var context_1 = createInferenceContext(root.inferTypeParameters, undefined, 0); if (!isDeferred) { - inferTypes(context.inferences, checkType, extendsType, 32 | 64); + inferTypes(context_1.inferences, checkType, extendsType, 32 | 64); } - combinedMapper = combineTypeMappers(mapper, context); + combinedMapper = combineTypeMappers(mapper, context_1); } if (!isDeferred) { if (checkType.flags & 1) { @@ -29350,7 +28551,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var checkType = getTypeFromTypeNode(node.checkType); - var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); var allOuterTypeParameters = getOuterTypeParameters(node, true); var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); var root = { @@ -29363,7 +28565,7 @@ var ts; inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, - aliasSymbol: getAliasSymbolForTypeNode(node), + aliasSymbol: aliasSymbol, aliasTypeArguments: aliasTypeArguments }; links.resolvedType = getConditionalType(root, undefined); @@ -29460,7 +28662,7 @@ var ts; else { var type = createObjectType(16, node.symbol); type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { type = createArrayType(type); } @@ -29470,10 +28672,9 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 236 ? getSymbolOfNode(node.parent) : undefined; + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); + function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } function getSpreadType(left, right, symbol, typeFlags, objectFlags) { @@ -29641,8 +28842,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119: - case 276: - case 277: + case 278: + case 279: return anyType; case 137: return stringType; @@ -29683,21 +28884,22 @@ var ts; return getTypeFromUnionTypeNode(node); case 169: return getTypeFromIntersectionTypeNode(node); - case 278: - return getTypeFromJSDocNullableTypeNode(node); case 280: + return getTypeFromJSDocNullableTypeNode(node); + case 282: return addOptionality(getTypeFromTypeNode(node.type)); case 172: - case 279: - case 275: + case 281: + case 277: return getTypeFromTypeNode(node.type); - case 282: + case 284: return getTypeFromJSDocVariadicType(node); case 162: case 163: case 165: - case 284: - case 281: + case 286: + case 283: + case 287: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 174: return getTypeFromTypeOperatorNode(node); @@ -29862,6 +29064,15 @@ var ts; var typeParameters = links.outerTypeParameters; if (!typeParameters) { var declaration_1 = symbol.declarations[0]; + if (ts.isInJavaScriptFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } var outerTypeParameters = getOuterTypeParameters(declaration_1, true); if (isJavaScriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); @@ -29897,8 +29108,8 @@ var ts; } function isTypeParameterPossiblyReferenced(tp, node) { if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_2 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 212 ? "quit" : n === container_2; })) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 212 ? "quit" : n === container_3; })) { return ts.forEachChild(node, containsReference); } } @@ -30626,7 +29837,7 @@ var ts; if (discriminant) { return hasExcessProperties(source, discriminant, undefined, reportErrors); } - var _loop_5 = function (prop) { + var _loop_6 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { ts.Debug.assert(!!errorNode); @@ -30657,7 +29868,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_5(prop); + var state_3 = _loop_6(prop); if (typeof state_3 === "object") return state_3.value; } @@ -30931,15 +30142,18 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || constraint.flags & 1) { + if (!constraint || (source.flags & 32768 && constraint.flags & 1)) { if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~134217728))) { errorInfo = saveErrorInfo; return result; } } - else if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var instantiated = getTypeWithThisArgument(constraint, source); + if (result = isRelatedTo(instantiated, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else if (source.flags & 524288) { @@ -31035,10 +30249,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_1; - if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -32900,7 +32114,7 @@ var ts; if (type.flags & 131072) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 268435456); } return f(type) ? type : neverType; } @@ -33938,7 +33152,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 281) { + if (jsdocType && jsdocType.kind === 283) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -34270,7 +33484,7 @@ var ts; case 54: var type = getContextualType(binaryExpression); return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? - getTypeOfExpression(left, true) : type; + getTypeOfExpression(left) : type; case 53: case 26: return node === right ? getContextualType(binaryExpression) : undefined; @@ -34497,8 +33711,18 @@ var ts; return unknownType; } } - if (context.typeArguments) { - signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + var links = getNodeLinks(context); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(valueType); + var cachedResolved = links.resolvedSignatures.get(cacheKey); + if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { + signatures = cachedResolved; + } + else if (!cachedResolved) { + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); } return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0); } @@ -34748,7 +33972,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 179 || contextualType.pattern.kind === 183); - var isInJSFile = ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; @@ -35239,6 +34463,33 @@ var ts; } return undefined; } + function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { + var links = getNodeLinks(openingLikeElement); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(elementType); + if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { + return; + } + else if (links.resolvedSignatures.get(cacheKey)) { + return links.resolvedSignatures.get(cacheKey); + } + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + var signatures = getSignaturesOfType(elementType, 1); + if (signatures.length === 0) { + signatures = getSignaturesOfType(elementType, 0); + if (signatures.length === 0) { + if (reportErrors) { + error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); + } + return; + } + } + var results = instantiateJsxSignatures(openingLikeElement, signatures); + links.resolvedSignatures.set(cacheKey, results); + return results; + } function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType.flags & 131072) { var types = elementType.types; @@ -35268,15 +34519,10 @@ var ts; } return anyType; } - var signatures = getSignaturesOfType(elementType, 1); - if (signatures.length === 0) { - signatures = getSignaturesOfType(elementType, 0); - if (signatures.length === 0) { - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - return unknownType; - } + var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, true); + if (!ts.length(instantiatedSignatures)) { + return unknownType; } - var instantiatedSignatures = instantiateJsxSignatures(openingLikeElement, signatures); var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : @@ -35426,7 +34672,7 @@ var ts; else if (!isSourceAttributeTypeAssignableToTarget) { if (ts.length(openingLikeElement.attributes.properties)) { var reportedError = false; - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (ts.isJsxSpreadAttribute(prop)) return "continue"; var name = ts.idText(prop.name); @@ -35439,7 +34685,7 @@ var ts; }; for (var _b = 0, _c = openingLikeElement.attributes.properties; _b < _c.length; _b++) { var prop = _c[_b]; - _loop_6(prop); + _loop_7(prop); } if (reportedError) { return; @@ -36408,9 +35654,9 @@ var ts; var isDecorator = node.kind === 149; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; - if (!isDecorator && !isJsxOpeningOrSelfClosingElement) { + if (!isDecorator) { typeArguments = node.typeArguments; - if (isTaggedTemplate || node.expression.kind !== 97) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97) { ts.forEach(typeArguments, checkSourceElement); } } @@ -36799,18 +36045,6 @@ var ts; } function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { ts.Debug.assert(!(elementType.flags & 131072)); - return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - } - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - if (elementType.flags & 131072) { - var types = elementType.types; - var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); - } - return result; - } var callSignatures = elementType && getSignaturesOfType(elementType, 0); if (callSignatures && callSignatures.length > 0) { return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); @@ -36829,7 +36063,18 @@ var ts; return resolveDecorator(node, candidatesOutArray); case 256: case 255: - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; + var exprTypes = checkExpression(node.tagName); + return forEachType(exprTypes, function (exprType) { + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + if (sfcResult && sfcResult !== unknownSignature) { + return sfcResult; + } + var sigs = getInstantiatedJsxSignatures(node, exprType); + if (candidatesOutArray && ts.length(sigs)) { + candidatesOutArray.push.apply(candidatesOutArray, sigs); + } + return ts.length(sigs) ? sigs[0] : unknownSignature; + }) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -36990,8 +36235,8 @@ var ts; if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); - var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, false); + var file_4 = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file_4, originalSymbol, false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152, "default"); @@ -37399,7 +36644,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -37601,8 +36846,8 @@ var ts; } if (type.flags & 393216) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -38568,19 +37813,12 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (node.kind !== 159 && node.kind !== 281) { + if (node.kind !== 159 && node.kind !== 283) { registerForUnusedIdentifiersCheck(node); } } } function checkClassForDuplicateDeclarations(node) { - var Declaration; - (function (Declaration) { - Declaration[Declaration["Getter"] = 1] = "Getter"; - Declaration[Declaration["Setter"] = 2] = "Setter"; - Declaration[Declaration["Method"] = 4] = "Method"; - Declaration[Declaration["Property"] = 3] = "Property"; - })(Declaration || (Declaration = {})); var instanceNames = ts.createUnderscoreEscapedMap(); var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { @@ -38981,7 +38219,7 @@ var ts; n.parent.kind !== 234 && n.parent.kind !== 204 && n.flags & 4194304) { - if (!(flags & 2)) { + if (!(flags & 2) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { flags |= 1; } flags |= 2; @@ -39206,19 +38444,13 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { case 235: case 236: - case 292: + case 296: + case 291: return 2; case 238: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 @@ -39237,10 +38469,10 @@ var ts; case 242: case 245: case 244: - var result_2 = 0; + var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; case 231: case 181: case 233: @@ -39547,7 +38779,7 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDocTypedefTag(node) { + function checkJSDocTypeAliasTag(node) { if (!node.typeExpression) { error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } @@ -39645,7 +38877,13 @@ var ts; } } function registerForUnusedIdentifiersCheck(node) { - if (potentiallyUnusedIdentifiers) { + if (produceDiagnostics) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } potentiallyUnusedIdentifiers.push(node); } } @@ -39653,10 +38891,6 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 273: - case 238: - checkUnusedModuleMembers(node, addDiagnostic); - break; case 234: case 204: checkUnusedClassMembers(node, addDiagnostic); @@ -39665,6 +38899,8 @@ var ts; case 235: checkUnusedTypeParameters(node, addDiagnostic); break; + case 273: + case 238: case 212: case 240: case 219: @@ -39697,31 +38933,6 @@ var ts; } } } - function checkUnusedLocalsAndParameters(node, addDiagnostic) { - if (!(node.flags & 4194304)) { - node.locals.forEach(function (local) { - if (local.flags & 262144 ? (local.flags & 3 && !(local.isReferenced & 3)) : !local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148) { - var parameter = ts.getRootDeclaration(local.valueDeclaration); - var name = ts.getNameOfDeclaration(local.valueDeclaration); - if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - addDiagnostic(1, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } - } - else { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local), addDiagnostic); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { @@ -39731,10 +38942,8 @@ var ts; return; } } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); - } + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(0, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -39778,7 +38987,7 @@ var ts; } function checkUnusedTypeParameters(node, addDiagnostic) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304) && typeParameters && ts.last(getSymbolOfNode(node).declarations) === node) { + if (!(node.flags & 4194304) && ts.last(getSymbolOfNode(node).declarations) === node) { for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { @@ -39787,49 +38996,87 @@ var ts; } } } - function checkUnusedModuleMembers(node, addDiagnostic) { - if (!(node.flags & 4194304)) { - var unusedImports_1 = ts.createMap(); - node.locals.forEach(function (local) { - if (local.isReferenced || local.exportSymbol) - return; - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isAmbientModule(declaration)) - continue; - if (isImportedDeclaration(declaration)) { - var importClause = importClauseFromImported(declaration); - var key = String(getNodeId(importClause)); - var group_1 = unusedImports_1.get(key); - if (group_1) { - group_1[1].push(declaration); - } - else { - unusedImports_1.set(key, [importClause, [declaration]]); + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304) + return; + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + if (local.flags & 262144 ? !(local.flags & 3 && !(local.isReferenced & 3)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + if (parameter) { + var name = ts.getNameOfDeclaration(local.valueDeclaration); + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { + addDiagnostic(1, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); } } - }); - unusedImports_1.forEach(function (_a) { - var importClause = _a[0], unuseds = _a[1]; - var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { - for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { - var unused = unuseds_1[_i]; - errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); - } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } - else if (unuseds.length === 1) { - addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else if (unuseds.length === 1) { + addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else { + addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 : 0; + if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } - else { - addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl))); - } - }); - } + } + else if (bindingElements.length === 1) { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + } + else { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + }); } function isImportedDeclaration(node) { return node.kind === 244 || node.kind === 247 || node.kind === 245; @@ -40749,7 +39996,7 @@ var ts; for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { var declaration = declarations_6[_i]; var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - var numTypeParameters = ts.length(sourceParameters); + var numTypeParameters = sourceParameters.length; if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; } @@ -40884,7 +40131,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -40902,7 +40149,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -41655,9 +40902,9 @@ var ts; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } - var exports = getExportsOfModule(moduleSymbol); - if (exports) { - exports.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -41756,26 +41003,27 @@ var ts; return checkInferType(node); case 178: return checkImportType(node); - case 286: + case 289: return checkJSDocAugmentsTag(node); + case 296: + case 291: + return checkJSDocTypeAliasTag(node); case 292: - return checkJSDocTypedefTag(node); - case 288: return checkJSDocParameterTag(node); - case 281: + case 283: checkSignatureDeclaration(node); - case 279: + case 281: + case 280: case 278: - case 276: - case 277: - case 284: + case 279: + case 286: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 282: + case 284: checkJSDocVariadicType(node); return; - case 275: + case 277: return checkSourceElement(node.type); case 175: return checkIndexedAccessType(node); @@ -41884,9 +41132,9 @@ var ts; var parent = node.parent; var paramTag = parent.parent; if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { - var host_2 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_2) { - var lastParamDeclaration = ts.lastOrUndefined(host_2.parameters); + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -41940,6 +41188,9 @@ var ts; return ts.Debug.assertNever(kind); } } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { @@ -41950,25 +41201,19 @@ var ts; ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); deferredNodes = []; - if (produceDiagnostics) { - ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName)); - allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []); - } ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { if (unusedIsError(kind)) { diagnostics.add(diag); } }); } deferredNodes = undefined; - seenPotentiallyUnusedIdentifiers.clear(); - potentiallyUnusedIdentifiers = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -42226,10 +41471,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 288) { + if (entityName.parent.kind === 292) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 147 && entityName.parent.parent.kind === 291) { + if (entityName.parent.kind === 147 && entityName.parent.parent.kind === 295) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -42667,6 +41912,7 @@ var ts; function isRequiredInitializedParameter(parameter) { return strictNullChecks && !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && parameter.initializer && !ts.hasModifier(parameter, 92); } @@ -42904,7 +42150,22 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024); }, - getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); + var otherKind = accessor.kind === 156 ? 155 : 156; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 156 ? accessor : otherAccessor; + var getAccessor = accessor.kind === 155 ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 206 && node.parent.parent && node.parent.parent.kind === 267; @@ -42931,8 +42192,8 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; if (decl.symbol && decl.symbol.flags & meaning) { - var file = ts.getSourceFileOfNode(decl); - var typeReferenceDirective = fileToDirective.get(file.path); + var file_5 = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file_5.path); if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } @@ -42962,8 +42223,8 @@ var ts; } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var file = ts.getSourceFileOfNode(decl); - if (fileToDirective.has(file.path)) { + var file_6 = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file_6.path)) { return true; } } @@ -42980,23 +42241,23 @@ var ts; } function initializeTypeChecker() { for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - ts.bindSourceFile(file, compilerOptions); + var file_7 = _a[_i]; + ts.bindSourceFile(file_7, compilerOptions); } var augmentations; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { - var file = _c[_b]; - if (!ts.isExternalOrCommonJsModule(file)) { - mergeSymbolTable(globals, file.locals); + var file_8 = _c[_b]; + if (!ts.isExternalOrCommonJsModule(file_8)) { + mergeSymbolTable(globals, file_8.locals); } - if (file.patternAmbientModules && file.patternAmbientModules.length) { - patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + if (file_8.patternAmbientModules && file_8.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file_8.patternAmbientModules); } - if (file.moduleAugmentations.length) { - (augmentations || (augmentations = [])).push(file.moduleAugmentations); + if (file_8.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file_8.moduleAugmentations); } - if (file.symbol && file.symbol.globalExports) { - var source = file.symbol.globalExports; + if (file_8.symbol && file_8.symbol.globalExports) { + var source = file_8.symbol.globalExports; source.forEach(function (sourceSymbol, id) { if (!globals.has(id)) { globals.set(id, sourceSymbol); @@ -43428,7 +42689,7 @@ var ts; } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(ts.getEffectiveTypeParameterDeclarations(node), file); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { if (!ts.isArrowFunction(node)) { @@ -43597,13 +42858,6 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var Flags; - (function (Flags) { - Flags[Flags["Property"] = 1] = "Property"; - Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; - Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; - Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; - })(Flags || (Flags = {})); var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; @@ -44065,8 +43319,8 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + if (ts.isNodeArray(typeParameters)) { + var pos = typeParameters.pos, end = typeParameters.end; return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } @@ -44191,7 +43445,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -44260,10 +43514,8 @@ var ts; if (!elements || elements === ts.emptyArray) { elements = []; } - else { - if (ts.isNodeArray(elements)) { - return elements; - } + else if (ts.isNodeArray(elements)) { + return elements; } var array = elements; array.pos = -1; @@ -44316,6 +43568,13 @@ var ts; node.text = text; return node; } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(12); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; function createLiteralFromNode(sourceNode) { var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; @@ -44349,7 +43608,7 @@ var ts; recordTempVariable(name); } if (reservedInNestedScopes) { - name.autoGenerateFlags |= 16; + name.autoGenerateFlags |= 8; } return name; } @@ -44372,7 +43631,7 @@ var ts; ts.createUniqueName = createUniqueName; function createOptimisticUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateFlags = 3 | 32; + name.autoGenerateFlags = 3 | 16; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -44380,18 +43639,15 @@ var ts; ts.createOptimisticUniqueName = createOptimisticUniqueName; function createFileLevelUniqueName(text) { var name = createOptimisticUniqueName(text); - name.autoGenerateFlags |= 64; + name.autoGenerateFlags |= 32; return name; } ts.createFileLevelUniqueName = createFileLevelUniqueName; - function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { - var name = createIdentifier(""); - name.autoGenerateFlags = 4; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 | flags; name.autoGenerateId = nextAutoGenerateId; name.original = node; - if (shouldSkipNameGenerationScope) { - name.autoGenerateFlags |= 8; - } nextAutoGenerateId++; return name; } @@ -44478,7 +43734,7 @@ var ts; ts.updateQualifiedName = updateQualifiedName; function parenthesizeForComputedName(expression) { return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26) || - expression.kind === 297 ? + expression.kind === 301 ? createParen(expression) : expression; } @@ -45518,6 +44774,12 @@ var ts; return block; } ts.createBlock = createBlock; + function createExpressionStatement(expression) { + var node = createSynthesizedNode(215); + node.expression = expression; + return node; + } + ts.createExpressionStatement = createExpressionStatement; function updateBlock(node, statements) { return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) @@ -45544,9 +44806,7 @@ var ts; } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(215); - node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); - return node; + return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression)); } ts.createStatement = createStatement; function updateStatement(node, expression) { @@ -46426,28 +45686,28 @@ var ts; } ts.getMutableClone = getMutableClone; function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295); + var node = createSynthesizedNode(299); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299); + var node = createSynthesizedNode(303); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(302); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296); + var node = createSynthesizedNode(300); node.expression = expression; node.original = original; setTextRange(node, original); @@ -46463,7 +45723,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297) { + if (node.kind === 301) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { @@ -46473,7 +45733,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(301); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -46484,15 +45744,31 @@ var ts; : node; } ts.updateCommaList = updateCommaList; - function createBundle(sourceFiles) { + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } var node = ts.createNode(274); + node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; - function updateBundle(node, sourceFiles) { - if (node.sourceFiles !== sourceFiles) { - return createBundle(sourceFiles); + function createUnparsedSourceFile(text) { + var node = ts.createNode(275); + node.text = text; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration) { + var node = ts.createNode(276); + node.javascriptText = javascript; + node.declarationText = declaration; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); } return node; } @@ -46694,6 +45970,15 @@ var ts; return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); } ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; function getConstantValue(node) { var emitNode = node.emitNode; return emitNode && emitNode.constantValue; @@ -47415,7 +46700,7 @@ var ts; function parenthesizeSubexpressionOfConditionalExpression(e) { var emittedExpression = ts.skipPartiallyEmittedExpressions(e); return emittedExpression.kind === 199 && emittedExpression.operatorToken.kind === 26 || - emittedExpression.kind === 297 + emittedExpression.kind === 301 ? ts.createParen(e) : e; } @@ -47424,7 +46709,7 @@ var ts; var check = ts.skipPartiallyEmittedExpressions(e); return (check.kind === 204 || check.kind === 191 || - check.kind === 297 || + check.kind === 301 || ts.isBinaryExpression(check) && check.operatorToken.kind === 26) ? ts.createParen(e) : e; @@ -47527,6 +46812,7 @@ var ts; switch (member.kind) { case 164: case 174: + case 171: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -47569,7 +46855,7 @@ var ts; case 184: node = node.expression; continue; - case 296: + case 300: node = node.expression; continue; } @@ -47583,13 +46869,6 @@ var ts; return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; - var OuterExpressionKinds; - (function (OuterExpressionKinds) { - OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; - OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; - OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; - OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; - })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7; } switch (node.kind) { @@ -47599,7 +46878,7 @@ var ts; case 207: case 208: return (kinds & 2) !== 0; - case 296: + case 300: return (kinds & 4) !== 0; } return false; @@ -47636,7 +46915,7 @@ var ts; case 189: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 207: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 208: return ts.updateNonNullExpression(outerExpression, expression); - case 296: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 300: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } function isIgnorableParen(node) { @@ -47984,7 +47263,7 @@ var ts; statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements); } var declarations = context.endLexicalEnvironment(); - return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); } ts.visitLexicalEnvironment = visitLexicalEnvironment; function visitParameterList(nodes, visitor, context, nodesVisitor) { @@ -48261,9 +47540,9 @@ var ts; return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); case 273: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 296: + case 300: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297: + case 301: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -48301,7 +47580,7 @@ var ts; case 214: case 205: case 230: - case 295: + case 299: break; case 145: result = reduceNode(node.left, cbNode, result); @@ -48664,10 +47943,10 @@ var ts; case 273: result = reduceNodes(node.statements, cbNodes, result); break; - case 296: + case 300: result = reduceNode(node.expression, cbNode, result); break; - case 297: + case 301: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -48681,8 +47960,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements) - : ts.addRange(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + : ts.prependRange(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function liftToBlock(nodes) { @@ -48802,16 +48081,6 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; - function getNamedImportCount(node) { - if (!(node.importClause && node.importClause.namedBindings)) - return 0; - var names = node.importClause.namedBindings; - if (!names) - return 0; - if (!ts.isNamedImports(names)) - return 0; - return names.elements.length; - } function containsDefaultReference(node) { if (!node) return false; @@ -48822,12 +48091,38 @@ var ts; function isNamedDefaultReference(e) { return e.propertyName && e.propertyName.escapedText === "default"; } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 273 ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; function getImportNeedsImportStarHelper(node) { - return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); } ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { - return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -48993,11 +48288,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var FlattenLevel; - (function (FlattenLevel) { - FlattenLevel[FlattenLevel["All"] = 0] = "All"; - FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; - })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; var value; @@ -49348,28 +48638,6 @@ var ts; var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; - var TypeScriptSubstitutionFlags; - (function (TypeScriptSubstitutionFlags) { - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; - })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); - var ClassFacts; - (function (ClassFacts) { - ClassFacts[ClassFacts["None"] = 0] = "None"; - ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; - ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; - ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; - ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; - ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; - ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; - ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; - ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; - ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; - ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; - ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; - })(ClassFacts || (ClassFacts = {})); function transformTypeScript(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -49392,7 +48660,21 @@ var ts; var classAliases; var applicableSubstitutions; var pendingExpressions; - return transformSourceFile; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 274) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276) { + return ts.createUnparsedSourceFile(prepend.javascriptText); + } + return prepend; + })); + } function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -49704,7 +48986,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.addRange(statements, context.endLexicalEnvironment()); + ts.prependRange(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ @@ -49780,7 +49062,7 @@ var ts; if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); var alias = ts.getSynthesizedClone(temp); - alias.autoGenerateFlags &= ~16; + alias.autoGenerateFlags &= ~8; classAliases[ts.getOriginalNodeId(node)] = alias; } ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); @@ -49907,7 +49189,7 @@ var ts; } function transformInitializedProperty(property, receiver) { var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) - ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32))) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); @@ -50526,6 +49808,9 @@ var ts; var innerExpression = ts.skipOuterExpressions(node.expression, ~2); if (ts.isAssertionExpression(innerExpression)) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } return ts.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -50586,8 +49871,9 @@ var ts; currentNamespaceContainerName = localName; var statements = []; startLexicalEnvironment(); - ts.addRange(statements, ts.map(node.members, transformEnumMember)); - ts.addRange(statements, endLexicalEnvironment()); + var members = ts.map(node.members, transformEnumMember); + ts.prependRange(statements, endLexicalEnvironment()); + ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); } @@ -50731,7 +50017,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -51071,10 +50357,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ES2017SubstitutionFlags; - (function (ES2017SubstitutionFlags) { - ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; - })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -51087,7 +50369,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -51301,7 +50583,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); if (languageVersion >= 2) { @@ -51321,7 +50603,7 @@ var ts; var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); } else { result = expression; @@ -51465,10 +50747,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ESNextSubstitutionFlags; - (function (ESNextSubstitutionFlags) { - ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; - })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); function transformESNext(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -51481,7 +50759,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -51558,9 +50836,14 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -51807,7 +51090,7 @@ var ts; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { @@ -51830,11 +51113,11 @@ var ts; statementOffset = ts.addPrologue(statements, body.statements, false, visitor); } ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(undefined, node)); - var trailingStatements = endLexicalEnvironment(); - if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) { + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, true); + ts.prependRange(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); - ts.addRange(statements, trailingStatements); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } return body; @@ -51966,7 +51249,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -51981,7 +51264,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -51991,7 +51274,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -52003,7 +51286,7 @@ var ts; function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -52457,7 +51740,7 @@ var ts; (function (ts) { function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -52517,75 +51800,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ES2015SubstitutionFlags; - (function (ES2015SubstitutionFlags) { - ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; - ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; - })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); - var CopyDirection; - (function (CopyDirection) { - CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; - CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; - })(CopyDirection || (CopyDirection = {})); - var Jump; - (function (Jump) { - Jump[Jump["Break"] = 2] = "Break"; - Jump[Jump["Continue"] = 4] = "Continue"; - Jump[Jump["Return"] = 8] = "Return"; - })(Jump || (Jump = {})); - var SuperCaptureResult; - (function (SuperCaptureResult) { - SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; - SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; - SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; - })(SuperCaptureResult || (SuperCaptureResult = {})); - var HierarchyFacts; - (function (HierarchyFacts) { - HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; - HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; - HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; - HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement"; - HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis"; - HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement"; - HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel"; - HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block"; - HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement"; - HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock"; - HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; - HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; - HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; - HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; - HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; - HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; - HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; - HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; - HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; - HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; - HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; - HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; - HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; - HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; - HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; - HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; - HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; - HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; - HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; - HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; - HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; - HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; - HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; - HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; - HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; - HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; - HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; - })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); @@ -52603,7 +51817,7 @@ var ts; } var convertedLoopState; var enabledSubstitutions; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -52767,7 +51981,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0, 0); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -52936,7 +52150,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); ts.setEmitFlags(block, 1536); return block; @@ -52999,7 +52213,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, false); } @@ -53395,12 +52609,13 @@ var ts; var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression); ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); ts.setEmitFlags(returnStatement, 384 | 32 | 1024); statements.push(returnStatement); closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); + ts.prependRange(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, false); if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { multiLine = true; @@ -53805,7 +53020,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1, statements_4); } - ts.addRange(statements_4, lexicalEnvironment); + ts.prependRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, true); } if (ts.isBlock(loopBody)) { @@ -54122,8 +53337,10 @@ var ts; } function visitTypeScriptClassWrapper(node) { var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); - var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); - var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); var variable = varStatement.declarationList.declarations[0]; var initializer = ts.skipOuterExpressions(variable.initializer); @@ -54518,7 +53735,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.enableSubstitution(184); context.enableSubstitution(269); - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { return node; } @@ -54572,51 +53789,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var OpCode; - (function (OpCode) { - OpCode[OpCode["Nop"] = 0] = "Nop"; - OpCode[OpCode["Statement"] = 1] = "Statement"; - OpCode[OpCode["Assign"] = 2] = "Assign"; - OpCode[OpCode["Break"] = 3] = "Break"; - OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; - OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; - OpCode[OpCode["Yield"] = 6] = "Yield"; - OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; - OpCode[OpCode["Return"] = 8] = "Return"; - OpCode[OpCode["Throw"] = 9] = "Throw"; - OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; - })(OpCode || (OpCode = {})); - var BlockAction; - (function (BlockAction) { - BlockAction[BlockAction["Open"] = 0] = "Open"; - BlockAction[BlockAction["Close"] = 1] = "Close"; - })(BlockAction || (BlockAction = {})); - var CodeBlockKind; - (function (CodeBlockKind) { - CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; - CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; - CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; - CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; - CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; - })(CodeBlockKind || (CodeBlockKind = {})); - var ExceptionBlockState; - (function (ExceptionBlockState) { - ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; - ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; - ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; - ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; - })(ExceptionBlockState || (ExceptionBlockState = {})); - var Instruction; - (function (Instruction) { - Instruction[Instruction["Next"] = 0] = "Next"; - Instruction[Instruction["Throw"] = 1] = "Throw"; - Instruction[Instruction["Return"] = 2] = "Return"; - Instruction[Instruction["Break"] = 3] = "Break"; - Instruction[Instruction["Yield"] = 4] = "Yield"; - Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; - Instruction[Instruction["Catch"] = 6] = "Catch"; - Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; - })(Instruction || (Instruction = {})); function getInstructionName(instruction) { switch (instruction) { case 2: return "return"; @@ -54658,7 +53830,7 @@ var ts; var exceptionBlockStack; var currentExceptionBlock; var withBlockStack; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; @@ -54842,7 +54014,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); inGeneratorFunctionBody = savedInGeneratorFunctionBody; inStatementContainingYield = savedInStatementContainingYield; @@ -56276,7 +55448,7 @@ var ts; var currentModuleInfo; var noSubstitution; var needUMDDynamicImportHelper; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { return node; @@ -56308,7 +55480,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, false); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); @@ -56423,7 +55595,7 @@ var ts; } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); @@ -56435,7 +55607,7 @@ var ts; } function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); if (expressionResult) { if (emitAsReturn) { var statement = ts.createReturn(expressionResult); @@ -56468,27 +55640,82 @@ var ts; return visitFunctionDeclaration(node); case 234: return visitClassDeclaration(node); - case 298: + case 302: return visitMergeDeclarationMarker(node); - case 299: + case 303: return visitEndOfDeclarationMarker(node); default: - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } - function importCallExpressionVisitor(node) { - if (!(node.transformFlags & 67108864)) { + function moduleExpressionElementVisitor(node) { + if (!(node.transformFlags & 67108864) && !(node.transformFlags & 2048)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } + else if (node.transformFlags & 1024 && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } else { - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 269: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 270: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 271: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 153: + case 155: + case 156: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0, false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } function visitImportCallExpression(node) { - var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); var containsLexicalThis = !!(node.transformFlags & 16384); switch (compilerOptions.module) { case ts.ModuleKind.AMD: @@ -56672,20 +55899,20 @@ var ts; var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), node, true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), node, true); } return ts.singleOrMany(statements); } function visitFunctionDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), node), node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -56699,10 +55926,10 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -56739,7 +55966,7 @@ var ts; } } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -56750,12 +55977,25 @@ var ts; } return ts.singleOrMany(statements); } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + ts.setEmitFlags(expression, 4); + expression = createExportExpression(exportName, expression, location); + } + return expression; + } + return ts.createAssignment(name, value); + } function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), undefined, context, 0, false, createExportExpression); + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), undefined, context, 0, false, createAllExportExpressions); } else { - return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); } } function visitMergeDeclarationMarker(node) { @@ -56987,8 +56227,8 @@ var ts; var exportedNames = getExports(node.left); if (exportedNames) { var expression = node; - for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { - var exportName = exportedNames_1[_i]; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression, node); } @@ -57008,8 +56248,8 @@ var ts; var expression = node.kind === 198 ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 ? 59 : 60), ts.createLiteral(1)), node) : node; - for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { - var exportName = exportedNames_2[_i]; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); } @@ -57085,7 +56325,7 @@ var ts; var hoistedStatements; var enclosingBlockScopedContainer; var noSubstitution; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { return node; @@ -57159,7 +56399,7 @@ var ts; ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); ts.addRange(statements, hoistedStatements); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -57243,11 +56483,11 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_2 = dependencyGroups_1[_i]; - var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var group_1 = dependencyGroups_1[_i]; + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -57606,9 +56846,9 @@ var ts; return visitCatchClause(node); case 212: return visitBlock(node); - case 298: + case 302: return visitMergeDeclarationMarker(node); - case 299: + case 303: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -57859,8 +57099,8 @@ var ts; var exportedNames = getExports(node.left); if (exportedNames) { var expression = node; - for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { - var exportName = exportedNames_3[_i]; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } return expression; @@ -57879,8 +57119,8 @@ var ts; var expression = node.kind === 198 ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; - for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { - var exportName = exportedNames_4[_i]; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } if (node.kind === 198) { @@ -57931,7 +57171,7 @@ var ts; context.enableEmitNotification(273); context.enableSubstitution(71); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -58395,7 +57635,12 @@ var ts; return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - var declarationEmitNodeBuilderFlags = 1024 | 2048 | 4096 | 8 | 524288; + var declarationEmitNodeBuilderFlags = 1024 | + 2048 | + 4096 | + 8 | + 524288 | + 4; function transformDeclarations(context) { var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; var getSymbolAccessibilityDiagnostic = throwDiagnostic; @@ -58409,19 +57654,22 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, - reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, }; var errorNameNode; var currentSourceFile; + var refs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); var noResolve = options.noResolve, stripInternal = options.stripInternal; - var host = context.getEmitHost(); return transformRoot; function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { if (!typeReferenceDirectives) { @@ -58433,6 +57681,10 @@ var ts; necessaryTypeRefernces.set(ref, true); } } + function trackReferencedAmbientModule(node) { + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } function handleSymbolAccessibilityError(symbolAccessibilityResult) { if (symbolAccessibilityResult.accessibility === 0) { if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { @@ -58460,6 +57712,8 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144) + return; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } @@ -58503,12 +57757,16 @@ var ts; resultHasExternalModuleIndicator = false; needsDeclare = false; var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], true, [], [], false); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], true, [], [], false); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - return ts.updateSourceFileNode(sourceFile, filterCandidateImports(updated), true, [], [], false); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), true, [], [], false); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276) { + return ts.createUnparsedSourceFile(prepend.declarationText); + } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); @@ -58530,13 +57788,13 @@ var ts; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); necessaryTypeRefernces = undefined; - var refs = collectReferences(currentSourceFile, ts.createMap()); + refs = collectReferences(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); - refs.forEach(referenceVisitor); var statements = ts.visitNodes(node.statements, visitDeclarationStatements); - var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); @@ -58547,17 +57805,19 @@ var ts; return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { - for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { - var importStatement = emittedImports_1[_i]; - if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { - var expr = importStatement.moduleReference.expression; - if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { return undefined; } } - else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { - return undefined; - } } return { fileName: typeName, pos: -1, end: -1 }; } @@ -58589,7 +57849,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); if (elem) { - ret.set("" + ts.getNodeId(elem), elem); + ret.set("" + ts.getOriginalNodeId(elem), elem); } }); return ret; @@ -58787,58 +58047,42 @@ var ts; return ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } } - function filterCandidateImports(statements) { - var unconsideredStatements = []; + function transformAndReplaceLatePaintedStatements(statements) { while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); - if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { - unconsideredStatements.push(i); - continue; - } if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was foudn which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); - } - switch (i.kind) { - case 242: { - var result = transformImportEqualsDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 243: { - var result = transformImportDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 213: { - var result = transformVariableStatement(i, true); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - default: ts.Debug.assertNever(i, "Unhandled late painted statement!"); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var result = transformTopLevelDeclaration(i, true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } - lateMarkedStatements = unconsideredStatements; return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); - } - function visitLateVisibilityMarkedStatements(statement) { - if (ts.isLateVisibilityPaintedStatement(statement)) { - var key = "" + ts.getNodeId(statement); - if (lateStatementReplacementMap.has(key)) { - var result = lateStatementReplacementMap.get(key); - lateStatementReplacementMap.delete(key); - if (result && ts.isSourceFile(statement.parent) && !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1)) { - needsScopeFixMarker = true; + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; } - return result; } - else { - return ts.getParseTreeNode(statement) ? undefined : statement; - } - } - else { return statement; } } + function isExternalModuleIndicator(result) { + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1) && !ts.isAmbientModule(result); + } function visitDeclarationSubtree(input) { if (shouldStripInternal(input)) return; @@ -59022,11 +58266,20 @@ var ts; return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } - case 242: + } + var result = transformTopLevelDeclaration(input); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 242: { + return transformImportEqualsDeclaration(input); + } case 243: { - lateMarkedStatements = lateMarkedStatements || []; - ts.pushIfUnique(lateMarkedStatements, input); - return input; + return transformImportDeclaration(input); } } if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) @@ -59038,44 +58291,44 @@ var ts; previousEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = input; } - var previousNeedsDeclare; var canProdiceDiagnostic = ts.canProduceDiagnostics(input); var oldDiag = getSymbolAccessibilityDiagnostic; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); } - var oldPossibleImports; + var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 236: - return cleanup(ts.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + return cleanup(ts.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 235: { - return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 233: { - return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); } case 238: { - previousNeedsDeclare = needsDeclare; needsDeclare = false; - oldPossibleImports = lateMarkedStatements; - lateMarkedStatements = undefined; var inner = input.body; if (inner && inner.kind === 239) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); - var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); return cleanup(ts.updateModuleDeclaration(input, undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); needsDeclare = false; - return cleanup(ts.updateModuleDeclaration(input, undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + ts.visitNode(inner, visitDeclarationStatements); + var id = "" + ts.getOriginalNodeId(inner); + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, undefined, mods, input.name, body)); } } case 234: { - var modifiers = ts.createNodeArray(ensureModifiers(input)); + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); var parameterProperties = void 0; @@ -59137,12 +58390,10 @@ var ts; } } case 213: { - var result = transformVariableStatement(input); - lateStatementReplacementMap.set("" + ts.getNodeId(input), result); - return cleanup(input); + return cleanup(transformVariableStatement(input, isPrivate)); } case 237: { - return cleanup(ts.updateEnumDeclaration(input, undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(ts.updateEnumDeclaration(input, undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; var constValue = resolver.getConstantValue(m); @@ -59151,26 +58402,20 @@ var ts; } } return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); - function cleanup(returnValue) { + function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; } - if (input.kind === 238) { - needsDeclare = previousNeedsDeclare; - lateMarkedStatements = ts.concatenate(oldPossibleImports, lateMarkedStatements); - } if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (returnValue && (!ts.isLateVisibilityPaintedStatement(input) || lateStatementReplacementMap.get("" + ts.getNodeId(input)))) { - if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1) && ts.isSourceFile(input.parent)) { - resultHasExternalModuleIndicator = true; - } + if (input.kind === 238) { + needsDeclare = previousNeedsDeclare; } - if (returnValue === input) { - return returnValue; + if (node === input) { + return node; } - return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } function transformVariableStatement(input, privateDeclaration) { @@ -59247,7 +58492,7 @@ var ts; return maskModifierFlags(node, mask, additions); } function ensureAccessor(node) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + var accessors = resolver.getAllAccessorDeclarations(node); if (node.kind !== accessors.firstAccessor.kind) { return; } @@ -59259,7 +58504,7 @@ var ts; var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -59273,7 +58518,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -59377,18 +58622,6 @@ var ts; return ts.transformModule; } } - var TransformationState; - (function (TransformationState) { - TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized"; - TransformationState[TransformationState["Initialized"] = 1] = "Initialized"; - TransformationState[TransformationState["Completed"] = 2] = "Completed"; - TransformationState[TransformationState["Disposed"] = 3] = "Disposed"; - })(TransformationState || (TransformationState = {})); - var SyntaxKindFeatureFlags; - (function (SyntaxKindFeatureFlags) { - SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; - SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; - })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); function getTransformers(compilerOptions, customTransformers) { var jsx = compilerOptions.jsx; var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -59421,7 +58654,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(300); + var enabledSyntaxKindFeatures = new Array(304); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -59798,7 +59031,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 295 + if (node.kind !== 299 && (emitFlags & 16) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -59815,7 +59048,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 295 + if (node.kind !== 299 && (emitFlags & 32) === 0 && end >= 0) { emitPos(end); @@ -59957,7 +59190,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295; + var isEmittedNode = node.kind !== 299; var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; if (!skipLeadingComments) { @@ -60252,13 +59485,14 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var bundle = ts.createBundle(sourceFiles); + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; @@ -60283,7 +59517,8 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); @@ -60291,14 +59526,23 @@ var ts; var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json"; + } if (options.jsx === 1) { if (ts.isSourceFileJavaScript(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { @@ -60311,7 +59555,8 @@ var ts; } return ".js"; } - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { + ts.getOutputExtension = getOutputExtension; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; @@ -60325,6 +59570,7 @@ var ts; mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, }); + var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; ts.performance.mark("beforePrint"); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); @@ -60336,8 +59582,8 @@ var ts; sourceMaps: sourceMapDataList }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -60349,10 +59595,12 @@ var ts; if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } } - function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { - var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { emitSkipped = true; return; @@ -60360,7 +59608,7 @@ var ts; if (emitOnlyDtsFiles) { return; } - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, false); + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, false); var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { hasGlobalName: resolver.hasGlobalName, onEmitNode: transform.emitNodeWithNotification, @@ -60370,7 +59618,8 @@ var ts; onEmitSourceMapOfPosition: sourceMap.emitPos, onSetSourceFile: setSourceFile, }); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { @@ -60379,8 +59628,8 @@ var ts; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); - var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; - var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], false); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), false); if (ts.length(declarationTransform.diagnostics)) { for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { var diagnostic = _b[_a]; @@ -60399,17 +59648,18 @@ var ts; var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], undefined, declarationPrinter, declarationSourceMap); } declarationTransform.dispose(); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 274 ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 273 ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { - printer.writeBundle(bundle, writer); + printer.writeBundle(bundle, writer, bundleInfo); } else { printer.writeFile(sourceFile, writer); @@ -60423,8 +59673,13 @@ var ts; ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), false, sourceFiles); } ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), false); + } mapRecorder.reset(); writer.clear(); + bundleInfo = createDefaultBundleInfo(); } function setSourceFile(node) { sourceMap.setSourceFile(node); @@ -60489,6 +59744,7 @@ var ts; switch (node.kind) { case 273: return printFile(node); case 274: return printBundle(node); + case 275: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -60505,6 +59761,10 @@ var ts; writeFile(sourceFile, beginPrint()); return endPrint(); } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; setWriter(output); @@ -60522,7 +59782,7 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output) { + function writeBundle(bundle, output, bundleInfo) { isOwnFileEmit = false; var previousWriter = writer; setWriter(output); @@ -60530,13 +59790,28 @@ var ts; emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); - for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { - var sourceFile = _b[_a]; + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + print(4, prepend, undefined); + writeLine(); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; print(0, sourceFile, sourceFile); } reset(); writer = previousWriter; } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output); + print(4, unparsed, undefined); + reset(); + writer = previousWriter; + } function writeFile(sourceFile, output) { isOwnFileEmit = true; var previousWriter = writer; @@ -60559,7 +59834,8 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmitWithNotification(hint, node); + var pipelinePhase = getPipelinePhase(0, hint); + pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -60582,386 +59858,396 @@ var ts; comments.reset(); setWriter(undefined); } - function emitIfPresent(node) { - if (node) { - emit(node); - } - } function emit(node) { - pipelineEmitWithNotification(4, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0, 4); + pipelinePhase(4, node); } function emitIdentifierName(node) { - pipelineEmitWithNotification(2, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0, 2); + pipelinePhase(2, node); } function emitExpression(node) { - pipelineEmitWithNotification(1, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0, 1); + pipelinePhase(1, node); + } + function getPipelinePhase(phase, hint) { + switch (phase) { + case 0: + if (onEmitNode) { + return pipelineEmitWithNotification; + } + case 1: + if (emitNodeWithComments && hint !== 0) { + return pipelineEmitWithComments; + } + return pipelineEmitWithoutComments; + case 2: + if (onEmitSourceMapOfNode && hint !== 0 && hint !== 2) { + return pipelineEmitWithSourceMap; + } + case 3: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + } + } + function getNextPipelinePhase(currentPhase, hint) { + return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - if (onEmitNode) { - onEmitNode(hint, node, pipelineEmitWithComments); - } - else { - pipelineEmitWithComments(hint, node); - } + ts.Debug.assertDefined(onEmitNode); + onEmitNode(hint, node, getNextPipelinePhase(0, hint)); } function pipelineEmitWithComments(hint, node) { - node = trySubstituteNode(hint, node); - if (emitNodeWithComments && hint !== 0) { - emitNodeWithComments(hint, node, pipelineEmitWithSourceMap); - } - else { - pipelineEmitWithSourceMap(hint, node); - } + ts.Debug.assertDefined(emitNodeWithComments); + ts.Debug.assert(hint !== 0); + emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1, hint)); + } + function pipelineEmitWithoutComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(1, hint); + pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - if (onEmitSourceMapOfNode && hint !== 0 && hint !== 2) { - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); - } - else { - pipelineEmitWithHint(hint, node); - } + ts.Debug.assertDefined(onEmitSourceMapOfNode); + ts.Debug.assert(hint !== 0 && hint !== 2); + onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { - switch (hint) { - case 0: return pipelineEmitSourceFile(node); - case 2: return pipelineEmitIdentifierName(node); - case 1: return pipelineEmitExpression(node); - case 3: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 4: return pipelineEmitUnspecified(node); + if (hint === 0) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 4) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + case 14: + case 15: + case 16: + return emitLiteral(node); + case 275: + return emitUnparsedSource(node); + case 71: + return emitIdentifier(node); + case 145: + return emitQualifiedName(node); + case 146: + return emitComputedPropertyName(node); + case 147: + return emitTypeParameter(node); + case 148: + return emitParameter(node); + case 149: + return emitDecorator(node); + case 150: + return emitPropertySignature(node); + case 151: + return emitPropertyDeclaration(node); + case 152: + return emitMethodSignature(node); + case 153: + return emitMethodDeclaration(node); + case 154: + return emitConstructor(node); + case 155: + case 156: + return emitAccessorDeclaration(node); + case 157: + return emitCallSignature(node); + case 158: + return emitConstructSignature(node); + case 159: + return emitIndexSignature(node); + case 160: + return emitTypePredicate(node); + case 161: + return emitTypeReference(node); + case 162: + return emitFunctionType(node); + case 283: + return emitJSDocFunctionType(node); + case 163: + return emitConstructorType(node); + case 164: + return emitTypeQuery(node); + case 165: + return emitTypeLiteral(node); + case 166: + return emitArrayType(node); + case 167: + return emitTupleType(node); + case 168: + return emitUnionType(node); + case 169: + return emitIntersectionType(node); + case 170: + return emitConditionalType(node); + case 171: + return emitInferType(node); + case 172: + return emitParenthesizedType(node); + case 206: + return emitExpressionWithTypeArguments(node); + case 173: + return emitThisType(); + case 174: + return emitTypeOperator(node); + case 175: + return emitIndexedAccessType(node); + case 176: + return emitMappedType(node); + case 177: + return emitLiteralType(node); + case 178: + return emitImportTypeNode(node); + case 278: + write("*"); + return; + case 279: + write("?"); + return; + case 280: + return emitJSDocNullableType(node); + case 281: + return emitJSDocNonNullableType(node); + case 282: + return emitJSDocOptionalType(node); + case 284: + return emitJSDocVariadicType(node); + case 179: + return emitObjectBindingPattern(node); + case 180: + return emitArrayBindingPattern(node); + case 181: + return emitBindingElement(node); + case 210: + return emitTemplateSpan(node); + case 211: + return emitSemicolonClassElement(); + case 212: + return emitBlock(node); + case 213: + return emitVariableStatement(node); + case 214: + return emitEmptyStatement(); + case 215: + return emitExpressionStatement(node); + case 216: + return emitIfStatement(node); + case 217: + return emitDoStatement(node); + case 218: + return emitWhileStatement(node); + case 219: + return emitForStatement(node); + case 220: + return emitForInStatement(node); + case 221: + return emitForOfStatement(node); + case 222: + return emitContinueStatement(node); + case 223: + return emitBreakStatement(node); + case 224: + return emitReturnStatement(node); + case 225: + return emitWithStatement(node); + case 226: + return emitSwitchStatement(node); + case 227: + return emitLabeledStatement(node); + case 228: + return emitThrowStatement(node); + case 229: + return emitTryStatement(node); + case 230: + return emitDebuggerStatement(node); + case 231: + return emitVariableDeclaration(node); + case 232: + return emitVariableDeclarationList(node); + case 233: + return emitFunctionDeclaration(node); + case 234: + return emitClassDeclaration(node); + case 235: + return emitInterfaceDeclaration(node); + case 236: + return emitTypeAliasDeclaration(node); + case 237: + return emitEnumDeclaration(node); + case 238: + return emitModuleDeclaration(node); + case 239: + return emitModuleBlock(node); + case 240: + return emitCaseBlock(node); + case 241: + return emitNamespaceExportDeclaration(node); + case 242: + return emitImportEqualsDeclaration(node); + case 243: + return emitImportDeclaration(node); + case 244: + return emitImportClause(node); + case 245: + return emitNamespaceImport(node); + case 246: + return emitNamedImports(node); + case 247: + return emitImportSpecifier(node); + case 248: + return emitExportAssignment(node); + case 249: + return emitExportDeclaration(node); + case 250: + return emitNamedExports(node); + case 251: + return emitExportSpecifier(node); + case 252: + return; + case 253: + return emitExternalModuleReference(node); + case 10: + return emitJsxText(node); + case 256: + case 259: + return emitJsxOpeningElementOrFragment(node); + case 257: + case 260: + return emitJsxClosingElementOrFragment(node); + case 261: + return emitJsxAttribute(node); + case 262: + return emitJsxAttributes(node); + case 263: + return emitJsxSpreadAttribute(node); + case 264: + return emitJsxExpression(node); + case 265: + return emitCaseClause(node); + case 266: + return emitDefaultClause(node); + case 267: + return emitHeritageClause(node); + case 268: + return emitCatchClause(node); + case 269: + return emitPropertyAssignment(node); + case 270: + return emitShorthandPropertyAssignment(node); + case 271: + return emitSpreadAssignment(node); + case 272: + return emitEnumMember(node); + } + if (ts.isExpression(node)) { + hint = 1; + node = trySubstituteNode(1, node); + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1) { + switch (node.kind) { + case 8: + return emitNumericLiteral(node); + case 9: + case 12: + case 13: + return emitLiteral(node); + case 71: + return emitIdentifier(node); + case 86: + case 95: + case 97: + case 101: + case 99: + case 91: + writeTokenNode(node, writeKeyword); + return; + case 182: + return emitArrayLiteralExpression(node); + case 183: + return emitObjectLiteralExpression(node); + case 184: + return emitPropertyAccessExpression(node); + case 185: + return emitElementAccessExpression(node); + case 186: + return emitCallExpression(node); + case 187: + return emitNewExpression(node); + case 188: + return emitTaggedTemplateExpression(node); + case 189: + return emitTypeAssertionExpression(node); + case 190: + return emitParenthesizedExpression(node); + case 191: + return emitFunctionExpression(node); + case 192: + return emitArrowFunction(node); + case 193: + return emitDeleteExpression(node); + case 194: + return emitTypeOfExpression(node); + case 195: + return emitVoidExpression(node); + case 196: + return emitAwaitExpression(node); + case 197: + return emitPrefixUnaryExpression(node); + case 198: + return emitPostfixUnaryExpression(node); + case 199: + return emitBinaryExpression(node); + case 200: + return emitConditionalExpression(node); + case 201: + return emitTemplateExpression(node); + case 202: + return emitYieldExpression(node); + case 203: + return emitSpreadExpression(node); + case 204: + return emitClassExpression(node); + case 205: + return; + case 207: + return emitAsExpression(node); + case 208: + return emitNonNullExpression(node); + case 209: + return emitMetaProperty(node); + case 254: + return emitJsxElement(node); + case 255: + return emitJsxSelfClosingElement(node); + case 258: + return emitJsxFragment(node); + case 300: + return emitPartiallyEmittedExpression(node); + case 301: + return emitCommaList(node); + } } - } - function pipelineEmitSourceFile(node) { - ts.Debug.assertNode(node, ts.isSourceFile); - emitSourceFile(node); - } - function pipelineEmitIdentifierName(node) { - ts.Debug.assertNode(node, ts.isIdentifier); - emitIdentifier(node); } function emitMappedTypeParameter(node) { emit(node.name); writeSpace(); writeKeyword("in"); writeSpace(); - emitIfPresent(node.constraint); - } - function pipelineEmitUnspecified(node) { - var kind = node.kind; - if (ts.isKeyword(kind)) { - writeTokenNode(node, writeKeyword); - return; - } - switch (kind) { - case 14: - case 15: - case 16: - return emitLiteral(node); - case 71: - return emitIdentifier(node); - case 145: - return emitQualifiedName(node); - case 146: - return emitComputedPropertyName(node); - case 147: - return emitTypeParameter(node); - case 148: - return emitParameter(node); - case 149: - return emitDecorator(node); - case 150: - return emitPropertySignature(node); - case 151: - return emitPropertyDeclaration(node); - case 152: - return emitMethodSignature(node); - case 153: - return emitMethodDeclaration(node); - case 154: - return emitConstructor(node); - case 155: - case 156: - return emitAccessorDeclaration(node); - case 157: - return emitCallSignature(node); - case 158: - return emitConstructSignature(node); - case 159: - return emitIndexSignature(node); - case 160: - return emitTypePredicate(node); - case 161: - return emitTypeReference(node); - case 162: - return emitFunctionType(node); - case 281: - return emitJSDocFunctionType(node); - case 163: - return emitConstructorType(node); - case 164: - return emitTypeQuery(node); - case 165: - return emitTypeLiteral(node); - case 166: - return emitArrayType(node); - case 167: - return emitTupleType(node); - case 168: - return emitUnionType(node); - case 169: - return emitIntersectionType(node); - case 170: - return emitConditionalType(node); - case 171: - return emitInferType(node); - case 172: - return emitParenthesizedType(node); - case 206: - return emitExpressionWithTypeArguments(node); - case 173: - return emitThisType(); - case 174: - return emitTypeOperator(node); - case 175: - return emitIndexedAccessType(node); - case 176: - return emitMappedType(node); - case 177: - return emitLiteralType(node); - case 178: - return emitImportTypeNode(node); - case 276: - write("*"); - return; - case 277: - write("?"); - return; - case 278: - return emitJSDocNullableType(node); - case 279: - return emitJSDocNonNullableType(node); - case 280: - return emitJSDocOptionalType(node); - case 282: - return emitJSDocVariadicType(node); - case 179: - return emitObjectBindingPattern(node); - case 180: - return emitArrayBindingPattern(node); - case 181: - return emitBindingElement(node); - case 210: - return emitTemplateSpan(node); - case 211: - return emitSemicolonClassElement(); - case 212: - return emitBlock(node); - case 213: - return emitVariableStatement(node); - case 214: - return emitEmptyStatement(); - case 215: - return emitExpressionStatement(node); - case 216: - return emitIfStatement(node); - case 217: - return emitDoStatement(node); - case 218: - return emitWhileStatement(node); - case 219: - return emitForStatement(node); - case 220: - return emitForInStatement(node); - case 221: - return emitForOfStatement(node); - case 222: - return emitContinueStatement(node); - case 223: - return emitBreakStatement(node); - case 224: - return emitReturnStatement(node); - case 225: - return emitWithStatement(node); - case 226: - return emitSwitchStatement(node); - case 227: - return emitLabeledStatement(node); - case 228: - return emitThrowStatement(node); - case 229: - return emitTryStatement(node); - case 230: - return emitDebuggerStatement(node); - case 231: - return emitVariableDeclaration(node); - case 232: - return emitVariableDeclarationList(node); - case 233: - return emitFunctionDeclaration(node); - case 234: - return emitClassDeclaration(node); - case 235: - return emitInterfaceDeclaration(node); - case 236: - return emitTypeAliasDeclaration(node); - case 237: - return emitEnumDeclaration(node); - case 238: - return emitModuleDeclaration(node); - case 239: - return emitModuleBlock(node); - case 240: - return emitCaseBlock(node); - case 241: - return emitNamespaceExportDeclaration(node); - case 242: - return emitImportEqualsDeclaration(node); - case 243: - return emitImportDeclaration(node); - case 244: - return emitImportClause(node); - case 245: - return emitNamespaceImport(node); - case 246: - return emitNamedImports(node); - case 247: - return emitImportSpecifier(node); - case 248: - return emitExportAssignment(node); - case 249: - return emitExportDeclaration(node); - case 250: - return emitNamedExports(node); - case 251: - return emitExportSpecifier(node); - case 252: - return; - case 253: - return emitExternalModuleReference(node); - case 10: - return emitJsxText(node); - case 256: - case 259: - return emitJsxOpeningElementOrFragment(node); - case 257: - case 260: - return emitJsxClosingElementOrFragment(node); - case 261: - return emitJsxAttribute(node); - case 262: - return emitJsxAttributes(node); - case 263: - return emitJsxSpreadAttribute(node); - case 264: - return emitJsxExpression(node); - case 265: - return emitCaseClause(node); - case 266: - return emitDefaultClause(node); - case 267: - return emitHeritageClause(node); - case 268: - return emitCatchClause(node); - case 269: - return emitPropertyAssignment(node); - case 270: - return emitShorthandPropertyAssignment(node); - case 271: - return emitSpreadAssignment(node); - case 272: - return emitEnumMember(node); - } - if (ts.isExpression(node)) { - return pipelineEmitExpression(trySubstituteNode(1, node)); - } - if (ts.isToken(node)) { - writeTokenNode(node, writePunctuation); - return; - } - } - function pipelineEmitExpression(node) { - var kind = node.kind; - switch (kind) { - case 8: - return emitNumericLiteral(node); - case 9: - case 12: - case 13: - return emitLiteral(node); - case 71: - return emitIdentifier(node); - case 86: - case 95: - case 97: - case 101: - case 99: - case 91: - writeTokenNode(node, writeKeyword); - return; - case 182: - return emitArrayLiteralExpression(node); - case 183: - return emitObjectLiteralExpression(node); - case 184: - return emitPropertyAccessExpression(node); - case 185: - return emitElementAccessExpression(node); - case 186: - return emitCallExpression(node); - case 187: - return emitNewExpression(node); - case 188: - return emitTaggedTemplateExpression(node); - case 189: - return emitTypeAssertionExpression(node); - case 190: - return emitParenthesizedExpression(node); - case 191: - return emitFunctionExpression(node); - case 192: - return emitArrowFunction(node); - case 193: - return emitDeleteExpression(node); - case 194: - return emitTypeOfExpression(node); - case 195: - return emitVoidExpression(node); - case 196: - return emitAwaitExpression(node); - case 197: - return emitPrefixUnaryExpression(node); - case 198: - return emitPostfixUnaryExpression(node); - case 199: - return emitBinaryExpression(node); - case 200: - return emitConditionalExpression(node); - case 201: - return emitTemplateExpression(node); - case 202: - return emitYieldExpression(node); - case 203: - return emitSpreadExpression(node); - case 204: - return emitClassExpression(node); - case 205: - return; - case 207: - return emitAsExpression(node); - case 208: - return emitNonNullExpression(node); - case 209: - return emitMetaProperty(node); - case 254: - return emitJsxElement(node); - case 255: - return emitJsxSelfClosingElement(node); - case 258: - return emitJsxFragment(node); - case 296: - return emitPartiallyEmittedExpression(node); - case 297: - return emitCommaList(node); - } + emit(node.constraint); } function trySubstituteNode(hint, node) { return node && substituteNode && substituteNode(hint, node) || node; @@ -61020,6 +60306,9 @@ var ts; writeStringLiteral(text); } } + function emitUnparsedSource(unparsed) { + write(unparsed.text); + } function emitIdentifier(node) { var writeText = node.symbol ? writeSymbol : write; writeText(getTextOfNode(node, false), node.symbol); @@ -61061,13 +60350,11 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.dotDotDotToken); - if (node.name) { - emitNodeWithWriter(node.name, writeParameter); - } - emitIfPresent(node.questionToken); - if (node.parent && node.parent.kind === 281 && !node.name) { - emitIfPresent(node.type); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 283 && !node.name) { + emit(node.type); } else { emitTypeAnnotation(node.type); @@ -61082,7 +60369,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeAnnotation(node.type); writeSemicolon(); } @@ -61090,28 +60377,30 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); - emitIfPresent(node.exclamationToken); + emit(node.questionToken); + emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -61128,14 +60417,17 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitCallSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitConstructSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("new"); @@ -61144,6 +60436,7 @@ var ts; emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); @@ -61167,18 +60460,20 @@ var ts; emitTypeArguments(node, node.typeArguments); } function emitFunctionType(node) { + pushNameGenerationScope(node); emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitJSDocFunctionType(node) { write("function"); emitParameters(node, node.parameters); write(":"); - emitIfPresent(node.type); + emit(node.type); } function emitJSDocNullableType(node) { write("?"); @@ -61193,6 +60488,7 @@ var ts; write("="); } function emitConstructorType(node) { + pushNameGenerationScope(node); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -61200,7 +60496,8 @@ var ts; writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitTypeQuery(node) { writeKeyword("typeof"); @@ -61290,7 +60587,8 @@ var ts; writeSpace(); } writePunctuation("["); - pipelineEmitWithNotification(3, node.typeParameter); + var pipelinePhase = getPipelinePhase(0, 3); + pipelinePhase(3, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); @@ -61300,7 +60598,7 @@ var ts; } writePunctuation(":"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); writeSemicolon(); if (emitFlags & 1) { writeSpace(); @@ -61340,7 +60638,7 @@ var ts; writePunctuation("]"); } function emitBindingElement(node) { - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); if (node.propertyName) { emit(node.propertyName); writePunctuation(":"); @@ -61355,6 +60653,7 @@ var ts; emitExpressionList(node, elements, 4466 | preferNewLine); } function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); @@ -61439,6 +60738,7 @@ var ts; emitTokenWithComment(20, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { @@ -61526,7 +60826,7 @@ var ts; } function emitYieldExpression(node) { emitTokenWithComment(116, node.pos, writeKeyword, node); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { @@ -61534,6 +60834,7 @@ var ts; emitExpression(node.expression); } function emitClassExpression(node) { + generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { @@ -61581,7 +60882,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - writeSemicolon(); + if (!ts.isJsonSourceFile(currentSourceFile)) { + writeSemicolon(); + } } function emitIfStatement(node) { var openParenPos = emitTokenWithComment(90, node.pos, writeKeyword, node); @@ -61774,7 +61077,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -61791,6 +61094,8 @@ var ts; increaseIndent(); } pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); emitSignatureHead(node); if (onEmitNode) { onEmitNode(4, body, emitBlockCallback); @@ -61879,6 +61184,7 @@ var ts; emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("class"); @@ -61956,6 +61262,7 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitBlockStatements(node, isEmptyBlock(node)); popNameGenerationScope(node); } @@ -61997,12 +61304,12 @@ var ts; writeSemicolon(); } function emitImportClause(node) { - emitIfPresent(node.name); + emit(node.name); if (node.name && node.namedBindings) { emitTokenWithComment(26, node.name.end, writePunctuation, node); writeSpace(); } - emitIfPresent(node.namedBindings); + emit(node.namedBindings); } function emitNamespaceImport(node) { var asPos = emitTokenWithComment(39, node.pos, writePunctuation, node); @@ -62138,7 +61445,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { writePunctuation("{"); - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); emitExpression(node.expression); writePunctuation("}"); } @@ -62271,8 +61578,8 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { - var directive = types_18[_d]; + for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { + var directive = types_17[_d]; write("/// "); writeLine(); } @@ -62280,6 +61587,7 @@ var ts; function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); @@ -62346,6 +61654,8 @@ var ts; } } function emitNodeWithWriter(node, writer) { + if (!node) + return; var savedWrite = write; write = writer; emit(node); @@ -62806,7 +62116,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return generateName(node); } - else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } else if (node.kind === 9 && node.textSourceNode) { @@ -62852,28 +62162,125 @@ var ts; } reservedNames.set(name, true); } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 212: + ts.forEach(node.statements, generateNames); + break; + case 227: + case 225: + case 217: + case 218: + generateNames(node.statement); + break; + case 216: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 219: + case 221: + case 220: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 226: + generateNames(node.caseBlock); + break; + case 240: + ts.forEach(node.clauses, generateNames); + break; + case 265: + case 266: + ts.forEach(node.statements, generateNames); + break; + case 229: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 268: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 213: + generateNames(node.declarationList); + break; + case 232: + ts.forEach(node.declarations, generateNames); + break; + case 231: + case 148: + case 181: + case 234: + generateNameIfNeeded(node.name); + break; + case 233: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 179: + case 180: + ts.forEach(node.elements, generateNames); + break; + case 243: + generateNames(node.importClause); + break; + case 244: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 245: + generateNameIfNeeded(node.name); + break; + case 246: + ts.forEach(node.elements, generateNames); + break; + case 247: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 269: + case 270: + case 151: + case 153: + case 155: + case 156: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } function generateName(name) { if ((name.autoGenerateFlags & 7) === 4) { - if (name.autoGenerateFlags & 8) { - var savedTempFlags = tempFlags; - popNameGenerationScope(undefined); - var result = generateNameCached(getNodeForGeneratedName(name)); - pushNameGenerationScope(undefined); - tempFlags = savedTempFlags; - return result; - } - else { - return generateNameCached(getNodeForGeneratedName(name)); - } + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); } else { var autoGenerateId = name.autoGenerateId; return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } - function generateNameCached(node) { + function generateNameCached(node, flags) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); } function isUniqueName(name) { return isFileLevelUniqueName(name) @@ -62881,7 +62288,7 @@ var ts; && !(reservedNames && reservedNames.has(name)); } function isFileLevelUniqueName(name) { - return ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName); + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; } function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { @@ -62921,11 +62328,16 @@ var ts; } } } - function makeUniqueName(baseName, checkFn, optimistic) { + function makeUniqueName(baseName, checkFn, optimistic, scoped) { if (checkFn === void 0) { checkFn = isUniqueName; } if (optimistic) { if (checkFn(baseName)) { - generatedNames.set(baseName, true); + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } return baseName; } } @@ -62936,7 +62348,12 @@ var ts; while (true) { var generatedName = baseName + i; if (checkFn(generatedName)) { - generatedNames.set(generatedName, true); + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } return generatedName; } i++; @@ -62967,10 +62384,10 @@ var ts; } return makeTempVariableName(0); } - function generateNameForNode(node) { + function generateNameForNode(node, flags) { switch (node.kind) { case 71: - return makeUniqueName(getTextOfNode(node)); + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16), !!(flags & 8)); case 238: case 237: return generateNameForModuleOrEnum(node); @@ -62994,11 +62411,11 @@ var ts; function makeName(name) { switch (name.autoGenerateFlags & 7) { case 1: - return makeTempVariableName(0, !!(name.autoGenerateFlags & 16)); + return makeTempVariableName(0, !!(name.autoGenerateFlags & 8)); case 2: - return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 16)); + return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 8)); case 3: - return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 64) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 32)); + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16), !!(name.autoGenerateFlags & 8)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -63009,7 +62426,7 @@ var ts; while (original) { node = original; if (ts.isIdentifier(node) - && node.autoGenerateFlags === 4 + && !!(node.autoGenerateFlags & 4) && node.autoGenerateId !== autoGenerateId) { break; } @@ -63033,12 +62450,6 @@ var ts; function getClosingBracket(format) { return brackets[format & 7680][1]; } - var TempFlags; - (function (TempFlags) { - TempFlags[TempFlags["Auto"] = 0] = "Auto"; - TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; - TempFlags[TempFlags["_i"] = 268435456] = "_i"; - })(TempFlags || (TempFlags = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -63065,7 +62476,7 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); } function getCachedFileSystemEntriesForBaseDir(path) { return getCachedFileSystemEntries(ts.getDirectoryPath(path)); @@ -63078,10 +62489,11 @@ var ts; files: ts.map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], directories: host.getDirectories(rootDir) || [] }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); return resultFromHost; } function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); var cachedResult = getCachedFileSystemEntries(rootDirPath); if (cachedResult) { return cachedResult; @@ -63090,7 +62502,7 @@ var ts; return createCachedFileSystemEntries(rootDir, rootDirPath); } catch (_e) { - ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); return undefined; } } @@ -63126,7 +62538,7 @@ var ts; } function directoryExists(dirPath) { var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); } function createDirectory(dirPath) { var path = toPath(dirPath); @@ -63366,7 +62778,7 @@ var ts; if (!commonPathComponents) { return currentDirectory; } - return ts.getNormalizedPathFromPathComponents(commonPathComponents); + return ts.getPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { @@ -63470,7 +62882,8 @@ var ts; directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, - realpath: realpath + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); } }; } ts.createCompilerHost = createCompilerHost; @@ -63536,45 +62949,45 @@ var ts; var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; - var context = ""; + var context_2 = ""; if (diagnostic.file) { - var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; - var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var start = diagnostic.start, length_4 = diagnostic.length, file_9 = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file_9, start + length_4), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file_9, file_9.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file_9.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_9.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; var gutterWidth = (lastLine + 1 + "").length; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } for (var i = firstLine; i <= lastLine; i++) { - context += host.getNewLine(); + context_2 += host.getNewLine(); if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context_2 += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); + var lineStart = ts.getPositionOfLineAndCharacter(file_9, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file_9, i + 1, 0) : file_9.text.length; + var lineContent = file_9.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); lineContent = lineContent.replace("\t", " "); - context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += lineContent + host.getNewLine(); - context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += ForegroundColorEscapeSequences.Red; + context_2 += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context_2 += lineContent + host.getNewLine(); + context_2 += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context_2 += ForegroundColorEscapeSequences.Red; if (i === firstLine) { var lastCharForLine = i === lastLine ? lastLineChar : undefined; - context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + context_2 += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context_2 += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); } else if (i === lastLine) { - context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + context_2 += lineContent.slice(0, lastLineChar).replace(/./g, "~"); } else { - context += lineContent.replace(/./g, "~"); + context_2 += lineContent.replace(/./g, "~"); } - context += resetEscapeSequence; + context_2 += resetEscapeSequence; } output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); output += ":"; @@ -63588,7 +63001,7 @@ var ts; output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); - output += context; + output += context_2; } output += host.getNewLine(); } @@ -63682,7 +63095,19 @@ var ts; oldOptions.baseUrl !== newOptions.baseUrl || !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); } - function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -63700,6 +63125,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -63708,6 +63134,7 @@ var ts; var supportedExtensions = ts.getSupportedExtensions(options); var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; + var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; @@ -63740,6 +63167,22 @@ var ts; var filesByName = ts.createMap(); var missingFilePaths; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + var resolvedProjectReferences = projectReferences ? [] : undefined; + var projectReferenceRedirects = ts.createMap(); + if (projectReferences) { + for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { + var ref = projectReferences_1[_i]; + var parsedRef = parseProjectReferenceConfigFile(ref); + resolvedProjectReferences.push(parsedRef); + if (parsedRef) { + if (parsedRef.commandLine.options.outFile) { + var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + processSourceFile(dtsOutfile, false, undefined); + } + addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + } + } + } var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { @@ -63769,8 +63212,8 @@ var ts; ts.Debug.assert(!!missingFilePaths); if (oldProgram && host.onReleaseOldSourceFile) { var oldSourceFiles = oldProgram.getSourceFiles(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); } @@ -63810,6 +63253,7 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -63827,6 +63271,10 @@ var ts; if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } + else if (options.composite) { + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } else { commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } @@ -63853,13 +63301,13 @@ var ts; } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } var unknownModuleNames; var result; @@ -63955,6 +63403,31 @@ var ts; if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { return oldProgram.structureIsReused = 0; } + var oldRefs = oldProgram.getProjectReferences(); + if (projectReferences) { + if (!oldRefs) { + return oldProgram.structureIsReused = 0; + } + for (var i = 0; i < projectReferences.length; i++) { + var oldRef = oldRefs[i]; + if (oldRef) { + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); + if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { + return oldProgram.structureIsReused = 0; + } + } + else { + if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + return oldProgram.structureIsReused = 0; + } + } + } + } + else { + if (oldRefs) { + return oldProgram.structureIsReused = 0; + } + } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; @@ -63963,11 +63436,6 @@ var ts; return oldProgram.structureIsReused = 0; } var oldSourceFiles = oldProgram.getSourceFiles(); - var SeenPackageName; - (function (SeenPackageName) { - SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; - SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; - })(SeenPackageName || (SeenPackageName = {})); var seenPackageNames = ts.createMap(); for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; @@ -64093,6 +63561,7 @@ var ts; } function getEmitHost(writeFileCallback) { return { + getPrependNodes: getPrependNodes, getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, @@ -64106,6 +63575,31 @@ var ts; isEmitBlocked: isEmitBlocked, }; } + function getProjectReferences() { + if (!resolvedProjectReferences) + return; + return resolvedProjectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + if (!resolvedRefOpts.options.outFile) + continue; + var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); + var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var node = ts.createInputFiles(js, dts); + nodes.push(node); + } + } + return nodes; + } function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } @@ -64163,7 +63657,7 @@ var ts; var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -64233,7 +63727,7 @@ var ts; ts.Debug.assert(!!sourceFile.bindDiagnostics); var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 || sourceFile.scriptKind === 4 || - sourceFile.scriptKind === 5 || isCheckJs; + sourceFile.scriptKind === 5 || isCheckJs || sourceFile.scriptKind === 7; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -64568,7 +64062,13 @@ var ts; var sourceFile = getSourceFile(fileName); if (fail) { if (!sourceFile) { - fail(ts.Diagnostics.File_0_not_found, fileName); + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); @@ -64627,26 +64127,35 @@ var ts; } function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { - var file_1 = filesByName.get(path); - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + var file_10 = filesByName.get(path); + if (file_10 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_10.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(fileName, file_10.fileName, refFile, refPos, refEnd); } - if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { - sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (file_10 && sourceFilesFoundSearchingNodeModules.get(file_10.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_10.path, false); if (!options.noResolve) { - processReferencedFiles(file_1, isDefaultLib); - processTypeReferenceDirectives(file_1); + processReferencedFiles(file_10, isDefaultLib); + processTypeReferenceDirectives(file_10); } - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); + modulesWithElidedImports.set(file_10.path, false); + processImportedModules(file_10); } - else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + else if (file_10 && modulesWithElidedImports.get(file_10.path)) { if (currentNodeModulesDepth < maxNodeModuleJsDepth) { - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); + modulesWithElidedImports.set(file_10.path, false); + processImportedModules(file_10); } } - return file_1; + return file_10; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + redirectedPath = toPath(redirect); + } } var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { @@ -64673,6 +64182,9 @@ var ts; } } filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; @@ -64701,6 +64213,20 @@ var ts; } return file; } + function getProjectReferenceRedirect(fileName) { + var path = toPath(fileName); + var normalized = ts.getNormalizedAbsolutePath(fileName, path); + var result; + projectReferenceRedirects.forEach(function (v, k) { + if (result !== undefined) { + return undefined; + } + if (normalized.indexOf(k) === 0) { + result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); + } + }); + return result; + } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); @@ -64709,6 +64235,9 @@ var ts; } function processTypeReferenceDirectives(file) { var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; @@ -64779,7 +64308,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -64813,9 +64342,9 @@ var ts; function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); + var file_11 = sourceFiles_2[_i]; + if (!file_11.isDeclarationFile) { + fileNames.push(file_11.fileName); } } return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); @@ -64837,6 +64366,25 @@ var ts; } return allFilesBelongToPath; } + function parseProjectReferenceConfigFile(ref) { + var refPath = resolveProjectReferencePath(host, ref); + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100); + if (sourceFile === undefined) { + return undefined; + } + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, undefined, refPath); + return { commandLine: commandLine, sourceFile: sourceFile }; + } + function addProjectReferenceRedirects(referencedProject, target) { + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); + target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); + } + function getDeclarationOutputDirectory(proj) { + return proj.options.declarationDir || + proj.options.outDir || + ts.getDirectoryPath(proj.options.configFilePath); + } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !options.strictNullChecks) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); @@ -64866,6 +64414,47 @@ var ts; if (options.paths && options.baseUrl === undefined) { createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + if (projectReferences) { + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; + if (resolvedRefOpts === undefined) { + createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); + continue; + } + if (!resolvedRefOpts.composite) { + createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + if (ref.prepend) { + if (resolvedRefOpts.outFile) { + if (!host.fileExists(resolvedRefOpts.outFile)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + } + } + else { + createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + } + } + if (options.composite && rootNames.length < files.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); + var _loop_10 = function (file_12) { + if (normalizedRootNames.every(function (r) { return r !== file_12; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file_12)); + } + }; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var file_12 = sourceFiles_4[_i]; + _loop_10(file_12); + } + } if (options.paths) { for (var key in options.paths) { if (!ts.hasProperty(options.paths, key)) { @@ -64954,6 +64543,11 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + } if (options.outDir || options.sourceRoot || options.mapRoot) { @@ -65056,12 +64650,15 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); } } - function getOptionPathsSyntax() { + function getOptionsSyntaxByName(name) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); if (compilerOptionsObjectLiteralSyntax) { - return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); } - return ts.emptyArray; + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; } function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(true, option1, option2, message, option1, option2, option3); @@ -65069,6 +64666,15 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(false, option1, undefined, message, arg0); } + function createDiagnosticForReference(index, message, arg0, arg1) { + var referencesSyntax = getProjectReferencesSyntax(); + if (referencesSyntax) { + if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { + return; + } + } + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || @@ -65077,11 +64683,28 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } + function getProjectReferencesSyntax() { + if (_referencesArrayLiteralSyntax === undefined) { + _referencesArrayLiteralSyntax = null; + if (options.configFile) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isArrayLiteralExpression(prop.initializer)) { + _referencesArrayLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _referencesArrayLiteralSyntax; + } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; - if (options.configFile && options.configFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { var prop = _a[_i]; if (ts.isObjectLiteralExpression(prop.initializer)) { _compilerOptionsObjectLiteralSyntax = prop.initializer; @@ -65100,6 +64723,12 @@ var ts; } return !!props.length; } + function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { + if (arrayLiteral.elements.length <= index) { + return false; + } + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -65131,11 +64760,29 @@ var ts; } } ts.createProgram = createProgram; + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + function resolveProjectReferencePath(host, ref) { + if (!host.fileExists(ref.path)) { + return ts.combinePaths(ref.path, "tsconfig.json"); + } + return ref.path; + } function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { case ".ts": case ".d.ts": + case ".json": return undefined; case ".tsx": return needJsx(); @@ -65298,6 +64945,7 @@ var ts; return !prevSignature || latestSignature !== prevSignature; } function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; var compilerOptions = programOfThisState.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { return getAllFileNames(state, programOfThisState); @@ -65314,7 +64962,7 @@ var ts; var references = state.referencedMap.get(path); if (references) { var iterator = references.keys(); - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { queue.push(value); } } @@ -65324,7 +64972,6 @@ var ts; var file = programOfThisState.getSourceFileByPath(path); return file ? file.fileName : path; })); - var _b; } BuilderState.getAllDependencies = getAllDependencies; function getAllFileNames(state, programOfThisState) { @@ -65646,8 +65293,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_1 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -65711,6 +65358,7 @@ var ts; startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, @@ -65869,6 +65517,10 @@ var ts; function resolveModuleNames(moduleNames, containingFile, reusedNames) { return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } @@ -65907,17 +65559,19 @@ var ts; if (isNodeModulesDirectory(dirPath)) { return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } + var subDirectory; if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { var parentPath = ts.getDirectoryPath(dirPath); if (parentPath === dirPath) { break; } + subDirectory = dirPath.slice(parentPath.length + ts.directorySeparator.length); dirPath = parentPath; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath, subDirectory: subDirectory }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -65936,7 +65590,7 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; @@ -65946,7 +65600,7 @@ var ts; setAtRoot = true; } else { - setDirectoryWatcher(dir, dirPath); + setDirectoryWatcher(dir, dirPath, subDirectory); } } } @@ -65954,13 +65608,19 @@ var ts; setDirectoryWatcher(rootDir, rootPath); } } - function setDirectoryWatcher(dir, dirPath) { + function setDirectoryWatcher(dir, dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { dirWatcher.refCount++; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }; + directoryWatchesOfFailedLookups.set(dirPath, dirWatcher); + } + if (subDirectory) { + var subDirectoryMap = dirWatcher.subDirectoryMap || (dirWatcher.subDirectoryMap = ts.createMap()); + var existing = subDirectoryMap.get(subDirectory) || 0; + subDirectoryMap.set(subDirectory, existing + 1); } } function stopWatchFailedLookupLocationOfResolution(resolution) { @@ -65976,7 +65636,7 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { @@ -65992,7 +65652,7 @@ var ts; removeAtRoot = true; } else { - removeDirectoryWatcher(dirPath); + removeDirectoryWatcher(dirPath, subDirectory); } } } @@ -66000,10 +65660,28 @@ var ts; removeDirectoryWatcher(rootPath); } } - function removeDirectoryWatcher(dirPath) { + function removeDirectoryWatcher(dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (subDirectory) { + var existing = dirWatcher.subDirectoryMap.get(subDirectory); + if (existing === 1) { + dirWatcher.subDirectoryMap.delete(subDirectory); + } + else { + dirWatcher.subDirectoryMap.set(subDirectory, existing - 1); + } + } dirWatcher.refCount--; } + function inWatchedSubdirectory(dirPath, fileOrDirectoryPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (!dirWatcher || !dirWatcher.subDirectoryMap) + return false; + return ts.forEachKey(dirWatcher.subDirectoryMap, function (subDirectory) { + var fullSubDirectory = dirPath + "/" + subDirectory; + return fullSubDirectory === fileOrDirectoryPath || isInDirectoryPath(fullSubDirectory, fileOrDirectoryPath); + }); + } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); @@ -66011,7 +65689,7 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } if (!allFilesHaveInvalidatedResolution && - dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + (dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath || inWatchedSubdirectory(dirPath, fileOrDirectoryPath))) { if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { resolutionHost.onInvalidatedResolution(); } @@ -66223,31 +65901,11 @@ var ts; function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; - var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - var result = ts.parseJsonText(configFileName, configFileText); - var cwd = host.getCurrentDirectory(); - return ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); - } - ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -66316,12 +65974,12 @@ var ts; watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, setTimeout: system.setTimeout ? (function (callback, ms) { + var _a; var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - var _a; }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, trace: function (s) { return system.write(s); }, @@ -67024,6 +66682,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, { name: "removeComments", type: "boolean", @@ -67274,6 +66939,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, { name: "listFiles", type: "boolean", @@ -67555,11 +67226,13 @@ var ts; function parseCommandLine(commandLine, readFile) { var options = {}; var fileNames = []; + var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, + projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -67667,6 +67340,26 @@ var ts; } return optionNameMap.get(optionName); } + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; function readConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; @@ -67701,69 +67394,84 @@ var ts; var _tsconfigRootOptions; function getTsconfigRootOptionsMap() { if (_tsconfigRootOptions === undefined) { - _tsconfigRootOptions = commandLineOptionsToMap([ - { - name: "compilerOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 - }, - { - name: "typingOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "typeAcquisition", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "extends", - type: "string" - }, - { - name: "files", - type: "list", - element: { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { name: "files", - type: "string" - } - }, - { - name: "include", - type: "list", - element: { + type: "list", + element: { + name: "files", + type: "string" + } + }, + { name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { + type: "list", + element: { + name: "include", + type: "string" + } + }, + { name: "exclude", - type: "string" - } - }, - ts.compileOnSaveCommandLineOption - ]); + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; } return _tsconfigRootOptions; } function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, undefined, undefined); + return convertToObjectWorker(sourceFile, errors, true, undefined, undefined); } ts.convertToObject = convertToObject; - function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.jsonObject) { - return {}; + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined); function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { - var result = {}; + var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; if (element.kind !== 269) { @@ -67783,16 +67491,18 @@ var ts; } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { - result[keyText] = value; + if (returnValue) { + result[keyText] = value; + } if (jsonConversionNotifier && - (parentOption || knownOptions === knownRootOptions)) { + (parentOption || isRootOptionMap(knownOptions))) { var isValidOptionValue = isCompilerOptionsValue(option, value); if (parentOption) { if (isValidOptionValue) { jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); } } - else if (knownOptions === knownRootOptions) { + else if (isRootOptionMap(knownOptions)) { if (isValidOptionValue) { jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); } @@ -67806,7 +67516,7 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -67872,6 +67582,7 @@ var ts; return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } + ts.convertToObjectWorker = convertToObjectWorker; function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : @@ -67913,7 +67624,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_9 = function (name) { + var _loop_11 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; @@ -67937,7 +67648,7 @@ var ts; } }; for (var name in options) { - _loop_9(name); + _loop_11(name); } return result; } @@ -68054,12 +67765,13 @@ var ts; var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); - options.configFilePath = configFileName; + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; return { options: options, fileNames: fileNames, + projectReferences: projectReferences, typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), raw: raw, errors: errors, @@ -68098,19 +67810,43 @@ var ts; createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } - else { - var outDir = raw.compilerOptions && raw.compilerOptions.outDir; - if (outDir) { - excludeSpecs = [outDir]; + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); } } if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + var references = []; + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + references.push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + result.projectReferences = references; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } return result; } function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { @@ -68218,7 +67954,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertToObjectWorker(sourceFile, errors, true, getTsconfigRootOptionsMap(), optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -68252,6 +67988,7 @@ var ts; return extendedConfigPath; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -68279,7 +68016,6 @@ var ts; mapPropertiesInRawIfNotUndefined("files"); } return extendedConfig; - var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { @@ -68304,7 +68040,7 @@ var ts; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function getDefaultCompilerOptions(configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {}; return options; @@ -68312,10 +68048,13 @@ var ts; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -68409,7 +68148,7 @@ var ts; validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { @@ -68423,27 +68162,31 @@ var ts; if (filesSpecs) { for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { var fileName = filesSpecs_1[_i]; - var file = ts.getNormalizedAbsolutePath(fileName, basePath); - literalFileMap.set(keyMapper(file), file); + var file_13 = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file_13), file_13); } } if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { - var file = _b[_a]; - if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + var file_14 = _b[_a]; + if (hasFileWithHigherPriorityExtension(file_14, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } - removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); - var key = keyMapper(file); + removeWildcardFilesWithLowerPriorityExtension(file_14, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file_14); if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { - wildcardFileMap.set(key, file); + wildcardFileMap.set(key, file_14); } } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { + return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); + }); return { fileNames: literalFiles.concat(wildcardFiles), + projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -68458,20 +68201,10 @@ var ts; return diag === undefined; }); function createDiagnostic(message, spec) { - if (jsonSourceFile && jsonSourceFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { - var property = _a[_i]; - if (ts.isArrayLiteralExpression(property.initializer)) { - for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (ts.isStringLiteral(element) && element.text === spec) { - return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); - } - } - } - } - } - return ts.createCompilerDiagnostic(message, spec); + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); } } function specToDiagnostic(spec, allowTrailingRecursion) { @@ -68489,8 +68222,8 @@ var ts; if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { - var file = include_1[_i]; - var spec = ts.normalizePath(ts.combinePaths(path, file)); + var file_15 = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file_15)); if (excludeRegex && excludeRegex.test(spec)) { continue; } @@ -68691,7 +68424,7 @@ var ts; createWatchOfConfigFile(configParseResult, commandLineOptions); } else { - performCompilation(configParseResult.fileNames, configParseResult.options, ts.getConfigFileParsingDiagnostics(configParseResult)); + performCompilation(configParseResult.fileNames, configParseResult.projectReferences, configParseResult.options, ts.getConfigFileParsingDiagnostics(configParseResult)); } } else { @@ -68701,7 +68434,7 @@ var ts; createWatchOfFilesAndCompilerOptions(commandLine.fileNames, commandLineOptions); } else { - performCompilation(commandLine.fileNames, commandLineOptions); + performCompilation(commandLine.fileNames, undefined, commandLineOptions); } } } @@ -68712,10 +68445,17 @@ var ts; ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } - function performCompilation(rootFileNames, compilerOptions, configFileParsingDiagnostics) { - var compilerHost = ts.createCompilerHost(compilerOptions); - enableStatistics(compilerOptions); - var program = ts.createProgram(rootFileNames, compilerOptions, compilerHost, undefined, configFileParsingDiagnostics); + function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) { + var host = ts.createCompilerHost(options); + enableStatistics(options); + var programOptions = { + rootNames: rootNames, + options: options, + projectReferences: projectReferences, + host: host, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + var program = ts.createProgram(programOptions); var exitStatus = ts.emitFilesAndReportErrors(program, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }); reportStatistics(program); return ts.sys.exit(exitStatus); @@ -68923,5 +68663,3 @@ if (ts.sys.setBlocking) { ts.sys.setBlocking(); } ts.executeCommandLine(ts.sys.args); - -//# sourceMappingURL=tsc.js.map diff --git a/lib/tsserver.js b/lib/tsserver.js index 51390899ad8..dc5875cc4b9 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -321,32 +321,36 @@ var ts; SyntaxKind[SyntaxKind["EnumMember"] = 272] = "EnumMember"; SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile"; SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle"; - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType"; - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 275] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 276] = "InputFiles"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 277] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 278] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 279] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 280] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 281] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 282] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 283] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 284] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 285] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 286] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 287] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 288] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 289] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 290] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 291] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 292] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 293] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 294] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 295] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 296] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 297] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["SyntaxList"] = 298] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 299] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 300] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 301] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 302] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 303] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 304] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -372,10 +376,10 @@ var ts; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 277] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 297] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 288] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 297] = "LastJSDocTagNode"; SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -406,6 +410,7 @@ var ts; NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; @@ -456,10 +461,9 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); var TokenFlags; (function (TokenFlags) { @@ -524,7 +528,9 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; @@ -770,6 +776,7 @@ var ts; TypeFlags[TypeFlags["ContainsObjectLiteral"] = 33554432] = "ContainsObjectLiteral"; TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType"; TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive"; + TypeFlags[TypeFlags["UnionOfUnitTypes"] = 268435456] = "UnionOfUnitTypes"; TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType"; TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; @@ -796,6 +803,7 @@ var ts; TypeFlags[TypeFlags["StructuredOrInstantiable"] = 8355840] = "StructuredOrInstantiable"; TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["NotUnit"] = 8374815] = "NotUnit"; TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening"; TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags"; TypeFlags[TypeFlags["NonWideningType"] = 16777216] = "NonWideningType"; @@ -922,6 +930,7 @@ var ts; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -932,6 +941,7 @@ var ts; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; @@ -1622,8 +1632,8 @@ var ts; return undefined; } ts.findLast = findLast; - function findIndex(array, predicate) { - for (var i = 0; i < array.length; i++) { + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -1631,6 +1641,15 @@ var ts; return -1; } ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; function findMap(array, callback) { for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); @@ -1961,6 +1980,23 @@ var ts; return false; } ts.some = some; + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; function concatenate(array1, array2) { if (!some(array2)) return array1; @@ -2151,6 +2187,15 @@ var ts; return to; } ts.addRange = addRange; + function prependRange(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + to.unshift.apply(to, from); + return to; + } + ts.prependRange = prependRange; function pushIfUnique(array, toAdd, equalityComparer) { if (contains(array, toAdd, equalityComparer)) { return false; @@ -2348,17 +2393,18 @@ var ts; } ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { + var _a; var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { result.push(map ? map(value) : value); } return result; - var _b; } ts.arrayFrom = arrayFrom; function forEachEntry(map, callback) { + var _a; var iterator = map.entries(); - for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { var key = pair[0], value = pair[1]; var result = callback(value, key); if (result) { @@ -2366,19 +2412,18 @@ var ts; } } return undefined; - var _b; } ts.forEachEntry = forEachEntry; function forEachKey(map, callback) { + var _a; var iterator = map.keys(); - for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { var result = callback(key); if (result) { return result; } } return undefined; - var _b; } ts.forEachKey = forEachKey; function copyEntries(source, target) { @@ -2847,11 +2892,11 @@ var ts; comparer(a[key], b[key]); } ts.compareProperties = compareProperties; - function getDiagnosticFileName(diagnostic) { - return diagnostic.file ? diagnostic.file.fileName : undefined; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; } function compareDiagnostics(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -2879,90 +2924,6 @@ var ts; } return text1 ? 1 : -1; } - function normalizeSlashes(path) { - return path.replace(/\\/g, "/"); - } - ts.normalizeSlashes = normalizeSlashes; - function getRootLength(path) { - if (path.charCodeAt(0) === 47) { - if (path.charCodeAt(1) !== 47) - return 1; - var p1 = path.indexOf("/", 2); - if (p1 < 0) - return 2; - var p2 = path.indexOf("/", p1 + 1); - if (p2 < 0) - return p1 + 1; - return p2 + 1; - } - if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92) - return 3; - } - if (path.lastIndexOf("file:///", 0) === 0) { - return "file:///".length; - } - var idx = path.indexOf("://"); - if (idx !== -1) { - return idx + "://".length; - } - return 0; - } - ts.getRootLength = getRootLength; - ts.directorySeparator = "/"; - var directorySeparatorCharCode = 47; - function getNormalizedParts(normalizedSlashedPath, rootLength) { - var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); - var normalized = []; - for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { - var part = parts_1[_i]; - if (part !== ".") { - if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { - normalized.pop(); - } - else { - if (part) { - normalized.push(part); - } - } - } - } - return normalized; - } - function normalizePath(path) { - return normalizePathAndParts(path).path; - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - var root = path.substr(0, rootLength); - var parts = getNormalizedParts(path, rootLength); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function pathEndsWithDirectorySeparator(path) { - return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; - } - ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; - function getDirectoryPath(path) { - return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function isUrl(path) { - return path && !isRootedDiskPath(path) && stringContains(path, "://"); - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -2994,6 +2955,10 @@ var ts; : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; } @@ -3013,181 +2978,351 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 && charCode <= 122) || + (charCode >= 65 && charCode <= 90); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58) + return start + 1; + if (ch0 === 37 && url.charCodeAt(start + 1) === 51) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 || ch2 === 65) + return start + 3; + } + return -1; + } + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + if (ch0 === 47 || ch0 === 92) { + if (path.charCodeAt(1) !== ch0) + return 1; + var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; + return p1 + 1; + } + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 || ch2 === 92) + return 3; + if (path.length === 2) + return 2; + } + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47) { + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); + } + return ~path.length; + } + return 0; + } + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function normalizePath(path) { + return resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; function isRootedDiskPath(path) { - return path && getRootLength(path) !== 0; + return getEncodedRootLength(path) > 0; } ts.isRootedDiskPath = isRootedDiskPath; + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); } ts.convertToRelativePath = convertToRelativePath; - function normalizedPathComponents(path, rootLength) { - var normalizedParts = getNormalizedParts(path, rootLength); - return [path.substr(0, rootLength)].concat(normalizedParts); + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); } - function getNormalizedPathComponents(path, currentDirectory) { - path = normalizeSlashes(path); + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); var rootLength = getRootLength(path); - if (rootLength === 0) { - path = combinePaths(normalizeSlashes(currentDirectory), path); - rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + function reducePathComponents(components) { + if (!some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); } - return normalizedPathComponents(path, rootLength); + return reduced; + } + ts.reducePathComponents = reducePathComponents; + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); } ts.getNormalizedPathComponents = getNormalizedPathComponents; function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); } ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getNormalizedPathFromPathComponents(pathComponents) { - if (pathComponents && pathComponents.length) { - return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); - } + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + if (pathComponents.length === 1) + return root; + return root + pathComponents.slice(1).join(ts.directorySeparator); } - ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; - function getNormalizedPathComponentsOfUrl(url) { - var urlLength = url.length; - var rootLength = url.indexOf("://") + "://".length; - while (rootLength < urlLength) { - if (url.charCodeAt(rootLength) === 47) { - rootLength++; - } - else { + ts.getPathFromPathComponents = getPathFromPathComponents; + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) break; - } } - if (rootLength === urlLength) { - return [url]; + if (start === 0) { + return toComponents; } - var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); - if (indexOfNextSlash !== -1) { - rootLength = indexOfNextSlash + 1; - return normalizedPathComponents(url, rootLength); - } - else { - return [url + ts.directorySeparator]; + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); } + return [""].concat(relative, components); } - function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { - if (isUrl(pathOrUrl)) { - return getNormalizedPathComponentsOfUrl(pathOrUrl); - } - else { - return getNormalizedPathComponents(pathOrUrl, currentDirectory); - } + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - directoryComponents.pop(); + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; } - var joinStartIndex; - for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { - break; - } - } - if (joinStartIndex) { - var relativePath = ""; - var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); - for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (directoryComponents[joinStartIndex] !== "") { - relativePath = relativePath + ".." + ts.directorySeparator; - } - } - return relativePath + relativePathComponents.join(ts.directorySeparator); - } - var absolutePath = getNormalizedPathFromPathComponents(pathComponents); - if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { - absolutePath = "file:///" + absolutePath; - } - return absolutePath; + return getPathFromPathComponents(pathComponents); } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function getRelativePath(path, directoryPath, getCanonicalFileName) { - var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ensurePathIsRelative(relativePath); + function ensurePathIsNonModuleName(path) { + return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path; } - ts.getRelativePath = getRelativePath; - function ensurePathIsRelative(path) { - return !pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsRelative = ensurePathIsRelative; - function getBaseFileName(path) { - if (path === undefined) { - return undefined; - } - var i = path.lastIndexOf(ts.directorySeparator); - return i < 0 ? path : path.substring(i + 1); + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; } ts.getBaseFileName = getBaseFileName; - function combinePaths(path1, path2) { - if (!(path1 && path1.length)) - return path2; - if (!(path2 && path2.length)) - return path1; - if (getRootLength(path2) !== 0) - return path2; - if (path1.charAt(path1.length - 1) === ts.directorySeparator) - return path1 + path2; - return path1 + ts.directorySeparator + path2; + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; } ts.combinePaths = combinePaths; + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 || ch === 92; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function removeTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) === ts.directorySeparator) { + if (hasTrailingDirectorySeparator(path)) { return path.substr(0, path.length - 1); } return path; } ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; function ensureTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) !== ts.directorySeparator) { + if (!hasTrailingDirectorySeparator(path)) { return path + ts.directorySeparator; } return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - function comparePaths(a, b, currentDirectory, ignoreCase) { + function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0; if (a === undefined) return -1; if (b === undefined) return 1; - a = removeTrailingDirectorySeparator(a); - b = removeTrailingDirectorySeparator(b); - var aComponents = getNormalizedPathComponents(a, currentDirectory); - var bComponents = getNormalizedPathComponents(b, currentDirectory); + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - var comparer = getStringComparer(ignoreCase); for (var i = 0; i < sharedLength; i++) { - var result = comparer(aComponents[i], bComponents[i]); + var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); if (result !== 0) { return result; } } return compareValues(aComponents.length, bComponents.length); } + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, getStringComparer(ignoreCase)); + } ts.comparePaths = comparePaths; function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } if (parent === undefined || child === undefined) return false; if (parent === child) return true; - parent = removeTrailingDirectorySeparator(parent); - child = removeTrailingDirectorySeparator(child); - if (parent === child) - return true; - var parentComponents = getNormalizedPathComponents(parent, currentDirectory); - var childComponents = getNormalizedPathComponents(child, currentDirectory); + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); if (childComponents.length < parentComponents.length) { return false; } - var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; + var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer; if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } @@ -3464,13 +3599,17 @@ var ts; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { - var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { - return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; + function isJavaScriptLike(scriptKind) { + return scriptKind === 1 || scriptKind === 2; + } function hasJavaScriptFileExtension(fileName) { return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } @@ -3529,7 +3668,7 @@ var ts; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; + var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx", ".json"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { var ext = extensionsToRemove_1[_i]; @@ -3550,9 +3689,14 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return (removeFileExtension(path) + newExtension); + return changeAnyExtension(path, newExtension, extensionsToRemove, false); } ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; function removeMinAndVersionNumbers(fileName) { var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); @@ -3811,6 +3955,10 @@ var ts; return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } ts.extensionIsTypeScript = extensionIsTypeScript; + function resolutionExtensionIsTypeScriptOrJson(ext) { + return extensionIsTypeScript(ext) || ext === ".json"; + } + ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); if (ext !== undefined) { @@ -3827,12 +3975,32 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPath(path) { + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive); + } var baseFileName = getBaseFileName(path); var extensionIndex = baseFileName.lastIndexOf("."); if (extensionIndex >= 0) { return baseFileName.substring(extensionIndex); } + return ""; } ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -3925,12 +4093,12 @@ var ts; ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; ts.missingFileModifiedTime = new Date(0); function createPollingIntervalBasedLevels(levels) { + var _a; return _a = {}, _a[PollingInterval.Low] = levels.Low, _a[PollingInterval.Medium] = levels.Medium, _a[PollingInterval.High] = levels.High, _a; - var _a; } var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); @@ -4247,6 +4415,7 @@ var ts; readDirectory: readDirectory, getModifiedTime: getModifiedTime, createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, getMemoryUsage: function () { if (global.gc) { global.gc(); @@ -4619,6 +4788,11 @@ var ts; hash.update(data); return hash.digest("hex"); } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -4921,7 +5095,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5398,6 +5572,7 @@ var ts; Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5581,6 +5756,17 @@ var ts; Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5679,6 +5865,7 @@ var ts; Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5742,6 +5929,12 @@ var ts; Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), }; })(ts || (ts = {})); var ts; @@ -7308,11 +7501,10 @@ var ts; } } function scanJSDocToken() { + startPos = tokenPos = pos; if (pos >= end) { return token = 1; } - startPos = pos; - tokenPos = pos; var ch = text.charCodeAt(pos); pos++; switch (ch) { @@ -7669,7 +7861,7 @@ var ts; if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 294 && node._children.length > 0) { + if (node.kind === 298 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -7844,12 +8036,12 @@ var ts; case 159: case 162: case 163: - case 281: + case 283: case 234: case 204: case 235: case 236: - case 291: + case 295: case 233: case 153: case 154: @@ -7857,6 +8049,9 @@ var ts; case 156: case 191: case 192: + case 291: + case 296: + case 287: return true; default: ts.assertTypeIsNever(node); @@ -7879,6 +8074,12 @@ var ts; case 243: case 242: case 213: + case 234: + case 233: + case 238: + case 236: + case 235: + case 237: return true; default: return false; @@ -7890,13 +8091,7 @@ var ts; } ts.isAnyImportOrReExport = isAnyImportOrReExport; function getEnclosingBlockScopeContainer(node) { - var current = node.parent; - while (current) { - if (isBlockScope(current, current.parent)) { - return current; - } - current = current.parent; - } + return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function declarationNameToString(name) { @@ -8006,6 +8201,8 @@ var ts; case 155: case 156: case 236: + case 151: + case 150: errorNode = node.name; break; case 192: @@ -8033,6 +8230,10 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6; + } + ts.isJsonSourceFile = isJsonSourceFile; function isConstEnumDeclaration(node) { return node.kind === 237 && isConst(node); } @@ -8344,6 +8545,23 @@ var ts; }); } ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.isObjectLiteralExpression(expression) && expression; + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral && + ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -8681,6 +8899,10 @@ var ts; return node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJsonFile(node) { + return node && !!(node.flags & 16777216); + } + ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { return node && !!(node.flags & 2097152); } @@ -8858,6 +9080,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243: case 249: @@ -8867,12 +9093,13 @@ var ts; case 186: return node.parent; case 177: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243: @@ -8921,12 +9148,20 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 281 && + return node.kind === 283 && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 296 || node.kind === 291; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && @@ -8948,6 +9183,8 @@ var ts; return v && v.initializer; case 151: return node.initializer; + case 269: + return node.initializer; } } function getSingleVariableOfVariableStatement(node) { @@ -8961,9 +9198,9 @@ var ts; node.body.kind === 238 && node.body; } - function getJSDocCommentsAndTags(node) { + function getJSDocCommentsAndTags(hostNode) { var result; - getJSDocCommentsAndTagsWorker(node); + getJSDocCommentsAndTagsWorker(hostNode); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; @@ -8972,8 +9209,7 @@ var ts; if (parent.kind === 269 || parent.kind === 151 || getNestedModuleDeclaration(parent)) { getJSDocCommentsAndTagsWorker(parent); } - if (parent.parent && - (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { + if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) { getJSDocCommentsAndTagsWorker(parent.parent); } if (parent.parent && parent.parent.parent && @@ -8982,15 +9218,15 @@ var ts; getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } - if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 || - ts.isBinaryExpression(parent) && getSpecialPropertyAssignmentKind(parent) !== 0 || + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 || node.kind === 184 && node.parent && node.parent.kind === 215) { getJSDocCommentsAndTagsWorker(parent); } if (node.kind === 148) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -9016,7 +9252,10 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - var host = getJSDocHost(node); + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || @@ -9025,18 +9264,9 @@ var ts; host; return decl && ts.isFunctionLike(decl) ? decl : undefined; } - ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; function getJSDocHost(node) { - while (node.parent.kind === 284) { - if (node.parent.parent.kind === 292) { - node = node.parent.parent; - } - else { - node = node.parent.parent.parent; - } - } - ts.Debug.assert(node.parent.kind === 283); - return node.parent.parent; + return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent; } ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { @@ -9051,7 +9281,8 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282; + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || type && type.kind === 284; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9182,8 +9413,14 @@ var ts; if (ts.isDeclaration(name.parent)) { return name.parent.name === name; } - var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + else if (ts.isQualifiedName(name.parent)) { + var tag = name.parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + } + else { + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + } default: return false; } @@ -9533,7 +9770,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 297: + case 301: return 0; case 203: return 1; @@ -9844,8 +10081,8 @@ var ts; }; } ts.createTextWriter = createTextWriter; - function getResolvedExternalModuleName(host, file) { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { @@ -9856,12 +10093,13 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - function getExternalModuleNameFromPath(host, fileName) { + function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); - return ts.removeFileExtension(relativePath); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { @@ -9943,7 +10181,7 @@ var ts; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { - if (signature.parameters.length) { + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { var thisParameter = signature.parameters[0]; if (parameterIsThisKeyword(thisParameter)) { return thisParameter; @@ -10020,16 +10258,33 @@ var ts; } ts.getTypeAnnotationNode = getTypeAnnotationNode; function getEffectiveReturnTypeNode(node) { + if (ts.isJSDocSignature(node)) { + return node.type && node.type.typeExpression && node.type.typeExpression.type; + } return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getEffectiveTypeParameterDeclarations(node) { - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 285); + var templateTags = ts.flatMap(ts.filter(node.parent.tags, ts.isJSDocTemplateTag), function (tag) { return tag.typeParameters; }); + var templateTagNodes = templateTags; + templateTagNodes.pos = templateTagNodes.length > 0 ? ts.first(templateTagNodes).pos : node.pos; + templateTagNodes.end = templateTagNodes.length > 0 ? ts.last(templateTagNodes).end : node.end; + templateTagNodes.hasTrailingComma = false; + return templateTagNodes; + } + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; + var tag = ts.find(ts.getJSDocTags(node), function (tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 && tag.parent.tags.some(isJSDocTypeAlias)); + }); + return (tag && tag.typeParameters) || ts.emptyArray; } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; function getEffectiveSetAccessorTypeAnnotationNode(node) { @@ -11154,8 +11409,8 @@ var ts; break; case 71: return declaration; - case 293: - case 288: { + case 297: + case 292: { var name = declaration.name; if (name.kind === 145) { return name.right; @@ -11174,7 +11429,9 @@ var ts; return undefined; } } - case 292: + case 291: + return declaration.name; + case 296: return getNameOfJSDocTypedef(declaration); case 248: { var expression = declaration.expression; @@ -11262,7 +11519,9 @@ var ts; function getJSDocTags(node) { var tags = node.jsDocCache; if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); } return tags; } @@ -11372,6 +11631,10 @@ var ts; return node.kind === 159; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 156 || node.kind === 155; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isTypePredicateNode(node) { return node.kind === 160; } @@ -11497,7 +11760,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296) { + while (node.kind === 300) { node = node.expression; } return node; @@ -11844,85 +12107,93 @@ var ts; } ts.isBundle = isBundle; function isJSDocTypeExpression(node) { - return node.kind === 275; + return node.kind === 277; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 276; + return node.kind === 278; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 277; + return node.kind === 279; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 278; + return node.kind === 280; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 279; + return node.kind === 281; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 280; + return node.kind === 282; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 281; + return node.kind === 283; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 282; + return node.kind === 284; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 283; + return node.kind === 285; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 286; + return node.kind === 289; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 287; + return node.kind === 290; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { - return node.kind === 288; + return node.kind === 292; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 289; + return node.kind === 293; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 290; + return node.kind === 294; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 291; + return node.kind === 295; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 292; + return node.kind === 296; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 293; + return node.kind === 297; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 293 || node.kind === 288; + return node.kind === 297 || node.kind === 292; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 284; + return node.kind === 286; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 291; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 287; + } + ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); (function (ts) { function isSyntaxList(n) { - return n.kind === 294; + return n.kind === 298; } ts.isSyntaxList = isSyntaxList; function isNode(node) { @@ -12044,10 +12315,11 @@ var ts; switch (kind) { case 152: case 157: + case 287: case 158: case 159: case 162: - case 281: + case 283: case 163: return true; default: @@ -12126,13 +12398,13 @@ var ts; || kind === 95 || kind === 131 || kind === 206 - || kind === 276 - || kind === 277 || kind === 278 || kind === 279 || kind === 280 || kind === 281 - || kind === 282; + || kind === 282 + || kind === 283 + || kind === 284; } function isTypeNode(node) { return isTypeNodeKind(node.kind); @@ -12319,8 +12591,8 @@ var ts; case 203: case 207: case 205: - case 297: - case 296: + case 301: + case 300: return true; default: return isUnaryExpressionKind(kind); @@ -12333,11 +12605,11 @@ var ts; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 296; + return node.kind === 300; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 295; + return node.kind === 299; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -12437,7 +12709,9 @@ var ts; || kind === 236 || kind === 147 || kind === 231 - || kind === 292; + || kind === 296 + || kind === 291 + || kind === 297; } function isDeclarationStatementKind(kind) { return kind === 233 @@ -12472,13 +12746,13 @@ var ts; || kind === 213 || kind === 218 || kind === 225 - || kind === 295 || kind === 299 - || kind === 298; + || kind === 303 + || kind === 302; } function isDeclaration(node) { if (node.kind === 147) { - return node.parent.kind !== 291 || ts.isInJavaScriptFile(node); + return node.parent.kind !== 295 || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -12556,15 +12830,15 @@ var ts; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isJSDocNode(node) { - return node.kind >= 275 && node.kind <= 293; + return node.kind >= 277 && node.kind <= 297; } ts.isJSDocNode = isJSDocNode; function isJSDocCommentContainingNode(node) { - return node.kind === 283 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node); + return node.kind === 285 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; function isJSDocTag(node) { - return node.kind >= 285 && node.kind <= 293; + return node.kind >= 288 && node.kind <= 297; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -12609,12 +12883,12 @@ var ts; case 231: case 233: case 236: - case 275: - case 278: - case 279: + case 277: case 280: case 281: case 282: + case 283: + case 284: return true; } return false; @@ -13081,7 +13355,7 @@ var ts; return visitNode(cbNode, node.expression); case 252: return visitNodes(cbNode, cbNodes, node.decorators); - case 297: + case 301: return visitNodes(cbNode, cbNodes, node.elements); case 254: return visitNode(cbNode, node.openingElement) || @@ -13108,23 +13382,23 @@ var ts; visitNode(cbNode, node.expression); case 257: return visitNode(cbNode, node.tagName); - case 275: + case 277: return visitNode(cbNode, node.type); - case 279: - return visitNode(cbNode, node.type); - case 278: + case 281: return visitNode(cbNode, node.type); case 280: return visitNode(cbNode, node.type); - case 281: - return visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); case 282: return visitNode(cbNode, node.type); case 283: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 284: + return visitNode(cbNode, node.type); + case 285: return visitNodes(cbNode, cbNodes, node.tags); - case 288: - case 293: + case 292: + case 297: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -13133,17 +13407,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } + case 293: + return visitNode(cbNode, node.typeExpression); + case 294: + return visitNode(cbNode, node.typeExpression); case 289: - return visitNode(cbNode, node.typeExpression); - case 290: - return visitNode(cbNode, node.typeExpression); - case 286: return visitNode(cbNode, node.class); - case 291: + case 295: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 292: + case 296: if (node.typeExpression && - node.typeExpression.kind === 275) { + node.typeExpression.kind === 277) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -13151,7 +13425,16 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 284: + case 291: + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 287: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 286: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -13159,7 +13442,7 @@ var ts; } } return; - case 296: + case 300: return visitNode(cbNode, node.expression); } } @@ -13167,7 +13450,13 @@ var ts; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + var result; + if (languageVersion === 100) { + result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + } ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; @@ -13224,6 +13513,13 @@ var ts; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined); + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + return result_1; + } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); @@ -13239,23 +13535,54 @@ var ts; return isInvalid ? entityName : undefined; } Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function parseJsonText(fileName, sourceText) { - initializeState(sourceText, 2, undefined, 6); + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2; } + initializeState(sourceText, languageVersion, syntaxCursor, 6); sourceFile = createSourceFile(fileName, 2, 6, false); - var result = sourceFile; nextToken(); + var pos = getNodePos(); if (token() === 1) { + sourceFile.statements = createNodeArray([], pos, pos); sourceFile.endOfFileToken = parseTokenNode(); } - else if (token() === 17 || - lookAhead(function () { return token() === 9; })) { - result.jsonObject = parseObjectLiteralExpression(); + else { + var statement = createNode(215); + switch (token()) { + case 21: + statement.expression = parseArrayLiteralExpression(); + break; + case 101: + case 86: + case 95: + statement.expression = parseTokenNode(); + break; + case 38: + if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 56; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8: + case 9: + if (lookAhead(function () { return nextToken() !== 56; })) { + statement.expression = parseLiteralNode(); + break; + } + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); sourceFile.endOfFileToken = parseExpectedToken(1, ts.Diagnostics.Unexpected_token); } - else { - parseExpected(17); + if (setParentNodes) { + fixupParentReferences(sourceFile); } sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; clearState(); return result; } @@ -13278,9 +13605,11 @@ var ts; switch (scriptKind) { case 1: case 2: - case 6: contextFlags = 65536; break; + case 6: + contextFlags = 65536 | 16777216; + break; default: contextFlags = 0; break; @@ -14270,9 +14599,9 @@ var ts; return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(276); + var result = createNode(278); if (postFixEquals) { - return createJSDocPostfixType(280, result); + return createJSDocPostfixType(282, result); } else { nextToken(); @@ -14280,7 +14609,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(279); + var result = createNode(281); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -14294,18 +14623,18 @@ var ts; token() === 29 || token() === 58 || token() === 49) { - var result = createNode(277, pos); + var result = createNode(279, pos); return finishNode(result); } else { - var result = createNode(278, pos); + var result = createNode(280, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(281); + var result = createNodeWithJSDoc(283); nextToken(); fillSignature(56, 4 | 32, result); return finishNode(result); @@ -14327,12 +14656,12 @@ var ts; var dotdotdot = parseOptionalToken(24); var type = parseType(); if (dotdotdot) { - var variadic = createNode(282, dotdotdot.pos); + var variadic = createNode(284, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } if (token() === 58) { - return createJSDocPostfixType(280, type); + return createJSDocPostfixType(282, type); } return type; } @@ -14400,10 +14729,11 @@ var ts; signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - signature.type = parseReturnType(returnToken, !!(flags & 4)); - } - function parseReturnType(returnToken, isType) { - return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + if (shouldParseReturnType(returnToken, !!(flags & 4))) { + signature.type = parseTypeOrTypePredicate(); + return signature.type !== undefined; + } + return true; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36) { @@ -14625,6 +14955,9 @@ var ts; var node = createNode(172); parseExpected(19); node.type = parseType(); + if (!node.type) { + return undefined; + } parseExpected(20); return finishNode(node); } @@ -14633,7 +14966,12 @@ var ts; if (kind === 163) { parseExpected(94); } - fillSignature(36, 4, node); + if (!fillSignature(36, 4 | (sourceFile.languageVariant === 1 ? 8 : 0), node)) { + return undefined; + } + if (!node.parameters) { + return undefined; + } return finishNode(node); } function parseKeywordAndNoDot() { @@ -14786,13 +15124,13 @@ var ts; while (!scanner.hasPrecedingLineBreak()) { switch (token()) { case 51: - type = createJSDocPostfixType(279, type); + type = createJSDocPostfixType(281, type); break; case 55: if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createJSDocPostfixType(278, type); + type = createJSDocPostfixType(280, type); break; case 21: parseExpected(21); @@ -15233,7 +15571,9 @@ var ts; var node = createNodeWithJSDoc(192); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); + if (!fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node)) { + return undefined; + } if (!node.parameters) { return undefined; } @@ -17166,7 +17506,7 @@ var ts; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(275, scanner.getTokenPos()); + var result = createNode(277, scanner.getTokenPos()); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17); result.type = doInsideOfContext(2097152, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -17186,6 +17526,7 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var _a; var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -17203,7 +17544,6 @@ var ts; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; - var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; var JSDocState; @@ -17214,8 +17554,9 @@ var ts; })(JSDocState || (JSDocState = {})); var PropertyLikeParse; (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; @@ -17258,7 +17599,7 @@ var ts; case 57: if (state === 0 || state === 1) { removeTrailingNewlines(comments); - parseTag(indent); + addTag(parseTag(indent)); state = 0; margin = undefined; indent++; @@ -17322,12 +17663,28 @@ var ts; } } function createJSDocComment() { - var result = createNode(283, start); + var result = createNode(285, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } + function isNextNonwhitespaceTokenEndOfFile() { + while (true) { + nextJSDocToken(); + if (token() === 1) { + return true; + } + if (!(token() === 5 || token() === 4)) { + return false; + } + } + } function skipWhitespace() { + if (token() === 5 || token() === 4) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; + } + } while (token() === 5 || token() === 4) { nextJSDocToken(); } @@ -17356,8 +17713,7 @@ var ts; case "arg": case "argument": case "param": - addTag(parseParameterOrPropertyTag(atToken, tagName, 1, indent)); - return; + return parseParameterOrPropertyTag(atToken, tagName, 2, indent); case "return": case "returns": tag = parseReturnTag(atToken, tagName); @@ -17369,7 +17725,10 @@ var ts; tag = parseTypeTag(atToken, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(atToken, tagName, indent); break; default: tag = parseUnknownTag(atToken, tagName); @@ -17382,8 +17741,10 @@ var ts; if (!tag) { return; } - tag.comment = parseTagComments(indent + tag.end - tag.pos); - addTag(tag); + if (!tag.comment) { + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; } function parseTagComments(indent) { var comments = []; @@ -17440,12 +17801,15 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { - var result = createNode(285, atToken.pos); + var result = createNode(288, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } function addTag(tag) { + if (!tag) { + return; + } if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -17494,8 +17858,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 ? - createNode(288, atToken.pos) : - createNode(293, atToken.pos); + createNode(297, atToken.pos) : + createNode(292, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -17515,18 +17879,18 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name, target) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(275, scanner.getTokenPos()); + var typeLiteralExpression = createNode(277, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 288 || child.kind === 293) { + if (child.kind === 292 || child.kind === 297) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(284, start_2); + jsdocTypeLiteral = createNode(286, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; if (typeExpression.type.kind === 166) { jsdocTypeLiteral.isArrayType = true; @@ -17537,27 +17901,27 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289; })) { + if (ts.forEach(tags, function (t) { return t.kind === 293; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(289, atToken.pos); + var result = createNode(293, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 290; })) { + if (ts.forEach(tags, function (t) { return t.kind === 294; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(290, atToken.pos); + var result = createNode(294, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var result = createNode(286, atToken.pos); + var result = createNode(289, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); @@ -17585,30 +17949,23 @@ var ts; return node; } function parseClassTag(atToken, tagName) { - var tag = createNode(287, atToken.pos); + var tag = createNode(290, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); } - function parseTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(292, atToken.pos); + var typedefTag = createNode(296, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 || !rightNode.body) { - typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); skipWhitespace(); + typedefTag.comment = parseTagComments(indent); typedefTag.typeExpression = typeExpression; + var end; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; @@ -17616,9 +17973,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(284, start_3); + jsdocTypeLiteral = createNode(286, start_3); } - if (child.kind === 290) { + if (child.kind === 294) { if (childTypeTag) { break; } @@ -17637,23 +17994,67 @@ var ts; typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; } } - return finishNode(typedefTag); - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(238, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); - return finishNode(jsDocNamespaceNode); + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23)) { + var jsDocNamespaceNode = createNode(238, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4; } - if (typeNameOrNamespaceName && flags & 4) { - typeNameOrNamespaceName.isInJSDocNamespace = true; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(true); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(atToken, tagName, indent) { + var callbackTag = createNode(291, atToken.pos); + callbackTag.atToken = atToken; + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var start = scanner.getStartPos(); + var jsdocSignature = createNode(287, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (token() === 57) { + nextJSDocToken(); + var tag = parseTag(indent); + if (tag && tag.kind === 293) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; } - return typeNameOrNamespaceName; } } function escapedTextsEqual(a, b) { @@ -17669,7 +18070,7 @@ var ts; return a.escapedText === b.escapedText; } function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(0); + return parseChildParameterOrPropertyTag(1); } function parseChildParameterOrPropertyTag(target, name) { var canParseTag = true; @@ -17679,7 +18080,8 @@ var ts; case 57: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 288 && + if (child && child.kind === 292 && + target !== 4 && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -17718,20 +18120,20 @@ var ts; var t; switch (tagName.escapedText) { case "type": - return target === 0 && parseTypeTag(atToken, tagName); + return target === 1 && parseTypeTag(atToken, tagName); case "prop": case "property": - t = 0; + t = 1; break; case "arg": case "argument": case "param": - t = 1; + t = 2 | 4; break; default: return false; } - if (target !== t) { + if (!(target & t)) { return false; } var tag = parseParameterOrPropertyTag(atToken, tagName, target, undefined); @@ -17763,7 +18165,7 @@ var ts; break; } } - var result = createNode(291, atToken.pos); + var result = createNode(295, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -17809,7 +18211,7 @@ var ts; var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); var result = createNode(71, pos); - result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); return result; @@ -18395,7 +18797,7 @@ var ts; var thisParentContainer; var blockScopeContainer; var lastContainer; - var delayedTypedefs; + var delayedTypeAliases; var seenThisKeyword; var currentFlow; var currentBreakTarget; @@ -18441,7 +18843,7 @@ var ts; thisParentContainer = undefined; blockScopeContainer = undefined; lastContainer = undefined; - delayedTypedefs = undefined; + delayedTypeAliases = undefined; seenThisKeyword = false; currentFlow = undefined; currentBreakTarget = undefined; @@ -18510,6 +18912,7 @@ var ts; return "__constructor"; case 162: case 157: + case 287: return "__call"; case 163: case 158: @@ -18518,22 +18921,21 @@ var ts; return "__index"; case 249: return "__export"; + case 273: + return "export="; case 199: if (ts.getSpecialPropertyAssignmentKind(node) === 2) { return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 281: + case 283: return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); case 148: - ts.Debug.assert(node.parent.kind === 281, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 283, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; - case 292: - var name_2 = ts.getNameOfJSDocTypedef(node); - return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } } function getDisplayName(node) { @@ -18613,9 +19015,9 @@ var ts; } } else { - if (node.kind === 292) + if (ts.isJSDocTypeAlias(node)) ts.Debug.assert(ts.isInJavaScriptFile(node)); - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || ts.isJSDocTypedefTag(node)) { + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } @@ -18752,20 +19154,6 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var j = _a[_i]; - bind(j); - } - } - else { - for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { - var j = _c[_b]; - setParentPointers(node, j); - } - } - } if (checkUnreachable(node)) { bindEachChild(node); return; @@ -18831,11 +19219,9 @@ var ts; case 186: bindCallExpressionFlow(node); break; - case 283: - bindJSDocComment(node); - break; - case 292: - bindJSDocTypedefTag(node); + case 296: + case 291: + bindJSDocTypeAlias(node); break; case 273: bindEachFunctionsFirst(node.statements); @@ -18849,6 +19235,7 @@ var ts; bindEachChild(node); break; } + bindJSDoc(node); } function isNarrowingExpression(expr) { switch (expr.kind) { @@ -19411,20 +19798,10 @@ var ts; bindInitializedVariableFlow(node); } } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 292) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - if (node.fullName && n === node.name && node.fullName.kind !== 71) { - return; - } - bind(n); - }); + function bindJSDocTypeAlias(node) { + if (node.fullName) { + setParentPointers(node, node.fullName); + } } function bindCallExpressionFlow(node) { var expr = node.expression; @@ -19453,7 +19830,7 @@ var ts; case 237: case 183: case 165: - case 284: + case 286: case 262: return 1; case 235: @@ -19474,7 +19851,8 @@ var ts; case 155: case 156: case 157: - case 281: + case 287: + case 283: case 162: case 158: case 159: @@ -19516,7 +19894,7 @@ var ts; case 237: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 165: - case 284: + case 286: case 183: case 235: case 262: @@ -19525,6 +19903,7 @@ var ts; case 163: case 157: case 158: + case 287: case 159: case 153: case 152: @@ -19534,7 +19913,9 @@ var ts; case 233: case 191: case 192: - case 281: + case 283: + case 296: + case 291: case 236: case 176: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); @@ -19683,22 +20064,35 @@ var ts; bindBlockScopedDeclaration(node, 2, 67216319); } function delayedBindJSDocTypedefTag() { - if (!delayedTypedefs) { + if (!delayedTypeAliases) { return; } var saveContainer = container; var saveLastContainer = lastContainer; var saveBlockScopeContainer = blockScopeContainer; var saveParent = parent; - for (var _i = 0, delayedTypedefs_1 = delayedTypedefs; _i < delayedTypedefs_1.length; _i++) { - var delay = delayedTypedefs_1[_i]; - (container = delay.container, lastContainer = delay.lastContainer, blockScopeContainer = delay.blockScopeContainer, parent = delay.parent); - bindBlockScopedDeclaration(delay.typedef, 524288, 67901928); + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 71) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288, 67901928); + } + else { + bind(typeAlias.fullName); + } } container = saveContainer; lastContainer = saveLastContainer; blockScopeContainer = saveBlockScopeContainer; parent = saveParent; + currentFlow = saveCurrentFlow; } function checkStrictModeIdentifier(node) { if (inStrictMode && @@ -19813,8 +20207,6 @@ var ts; } node.parent = parent; var saveInStrictMode = inStrictMode; - if (ts.isInJavaScriptFile(node)) - bindJSDocTypedefTagIfAny(node); bindWorker(node); if (node.kind > 144) { var saveParent = parent; @@ -19830,25 +20222,22 @@ var ts; } else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + bindJSDoc(node); } inStrictMode = saveInStrictMode; } - function bindJSDocTypedefTagIfAny(node) { - if (!ts.hasJSDocNodes(node)) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 292) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); } } } @@ -19876,7 +20265,7 @@ var ts; case 71: if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 292) { + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } bindBlockScopedDeclaration(parentNode, 524288, 67901928); @@ -19972,11 +20361,12 @@ var ts; case 156: return bindPropertyOrMethodOrAccessor(node, 65536, 67183551); case 162: - case 281: + case 283: + case 287: case 163: return bindFunctionOrConstructorType(node); case 165: - case 284: + case 286: case 176: return bindAnonymousTypeWorker(node); case 183: @@ -20027,23 +20417,22 @@ var ts; } case 239: return updateStrictModeStatementList(node.statements); - case 288: - if (node.parent.kind !== 284) { + case 292: + if (node.parent.kind === 287) { + return bindParameter(node); + } + if (node.parent.kind !== 286) { break; } - case 293: + case 297: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 280 ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 282 ? 4 | 16777216 : 4; return declareSymbolAndAddToSymbolTable(propTag, flags, 0); - case 292: { - var fullName = node.fullName; - if (!fullName || fullName.kind === 71) { - (delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node, container: container, lastContainer: lastContainer, blockScopeContainer: blockScopeContainer, parent: parent }); - } - break; - } + case 296: + case 291: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } function bindPropertyWorker(node) { @@ -20057,6 +20446,12 @@ var ts; if (ts.isExternalModule(file)) { bindSourceFileAsExternalModule(); } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4, 67108863); + file.symbol = originalSymbol; + } } function bindSourceFileAsExternalModule() { bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); @@ -20333,6 +20728,9 @@ var ts; } } function bindParameter(node) { + if (node.kind === 292 && container.kind !== 287) { + return; + } if (inStrictMode && !(node.flags & 4194304)) { checkStrictModeEvalOrArguments(node, node.name); } @@ -20387,24 +20785,30 @@ var ts; : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } function getInferTypeContainer(node) { - while (node) { - var parent_2 = node.parent; - if (parent_2 && parent_2.kind === 170 && parent_2.extendsType === node) { - return parent_2; - } - node = parent_2; - } - return undefined; + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; } function bindTypeParameter(node) { - if (node.parent.kind === 171) { - var container_1 = getInferTypeContainer(node.parent); + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); if (container_1) { if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } declareSymbol(container_1.locals, undefined, node, 262144, 67639784); } + else { + declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + } + } + else if (node.parent.kind === 171) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, undefined, node, 262144, 67639784); + } else { bindAnonymousDeclaration(node, 262144, getDeclarationName(node)); } @@ -20728,7 +21132,7 @@ var ts; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; - if (node.initializer) { + if (node.initializer || ts.isComputedPropertyName(node.name)) { transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; @@ -20907,7 +21311,7 @@ var ts; break; case 189: case 207: - case 296: + case 300: transformFlags |= 3; excludeFlags = 536872257; break; @@ -21140,7 +21544,7 @@ var ts; return 940049729; case 189: case 207: - case 296: + case 300: case 190: case 97: return 536872257; @@ -21154,7 +21558,7 @@ var ts; ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; function setParentPointers(parent, child) { child.parent = parent; - ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); } })(ts || (ts = {})); var ts; @@ -21338,7 +21742,8 @@ var ts; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; })(Extensions || (Extensions = {})); function resolvedTypeScriptOnly(resolved) { if (!resolved) { @@ -21379,7 +21784,13 @@ var ts; function readJson(path, host) { try { var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; } catch (e) { return {}; @@ -21789,7 +22200,11 @@ var ts; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + var result = jsOnly ? + tryResolve(Extensions.JavaScript) : + (tryResolve(Extensions.TypeScript) || + tryResolve(Extensions.JavaScript) || + (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); @@ -21842,7 +22257,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); if (!directoryProbablyExists(parentOfCandidate, state.host)) { @@ -21910,6 +22325,10 @@ var ts; return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); } function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (extensions === Extensions.Json) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json"); + return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + } var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; @@ -21937,6 +22356,8 @@ var ts; return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); case Extensions.JavaScript: return tryExtension(".js") || tryExtension(".jsx"); + case Extensions.Json: + return tryExtension(".json"); } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); @@ -21988,8 +22409,11 @@ var ts; } else { var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string") { - subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js"), ".jsx") + ".d.ts"; + if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { + var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts"; } else { subModuleName = "index.d.ts"; @@ -22021,9 +22445,17 @@ var ts; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); if (!file) { - return undefined; + if (extensions === Extensions.TypeScript) { + file = tryReadPackageJsonFields(false, jsonContent, candidate, state); + if (!file) { + return undefined; + } + } + else { + return undefined; + } } var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); @@ -22051,6 +22483,8 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" || extension === ".jsx"; + case Extensions.Json: + return extension === ".json"; case Extensions.TypeScript: return extension === ".ts" || extension === ".tsx" || extension === ".d.ts"; case Extensions.DtsOnly: @@ -22116,7 +22550,7 @@ var ts; if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript) { + if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { @@ -22503,7 +22937,7 @@ var ts; checkSourceFile(file); var diagnostics = []; ts.Debug.assert(!!(getNodeLinks(file).flags & 1)); - checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { if (!unusedIsError(kind)) { diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } @@ -22571,6 +23005,7 @@ var ts; var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); + var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); var globals = ts.createSymbolTable(); @@ -22607,8 +23042,6 @@ var ts; var deferredGlobalExtractSymbol; var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); - var potentiallyUnusedIdentifiers; - var seenPotentiallyUnusedIdentifiers = ts.createMap(); var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -23032,6 +23465,8 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864) { + var targetValueDeclaration = target.valueDeclaration; + ts.Debug.assert(!!(target.flags & 33554432)); if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; } @@ -23054,7 +23489,12 @@ var ts; } if ((source.flags | target.flags) & 67108864) { var sourceInitializer = ts.getJSInitializerSymbol(source); - var targetInitializer = ts.getJSInitializerSymbol(target); + var init = ts.getDeclaredJavascriptInitializer(targetValueDeclaration) || ts.getAssignedJavascriptInitializer(targetValueDeclaration); + var targetInitializer = init && init.symbol ? init.symbol : target; + if (!(targetInitializer.flags & 33554432)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } if (sourceInitializer !== source || targetInitializer !== target) { mergeSymbol(targetInitializer, sourceInitializer); } @@ -23285,7 +23725,7 @@ var ts; if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 67901928 && lastLocation.kind !== 283) { + if (meaning & result.flags & 67901928 && lastLocation.kind !== 285) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 148 || @@ -23427,6 +23867,11 @@ var ts; location = location.parent; } break; + case 296: + case 291: + lastLocation = location; + location = ts.getJSDocHost(location).parent; + continue; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -23524,9 +23969,11 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (decl.kind === 147 && parent === container) { - return true; + if (decl.kind === 147) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + } } } return false; @@ -23921,7 +24368,7 @@ var ts; var symbol; if (name.kind === 71) { var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSPrototype(name, meaning) : undefined; + var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); if (!symbol) { return symbolFromJSPrototype; @@ -23973,20 +24420,32 @@ var ts; ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } - function resolveEntityNameFromJSPrototype(name, meaning) { - if (isJSDocTypeReference(name.parent) && ts.isJSDocTag(name.parent.parent.parent)) { - var host_1 = ts.getJSDocHost(name.parent.parent.parent); - if (ts.isExpressionStatement(host_1) && - ts.isBinaryExpression(host_1.expression) && - ts.getSpecialPropertyAssignmentKind(host_1.expression) === 3) { - var symbol = getSymbolOfNode(host_1.expression.left); - if (symbol) { - var secondaryLocation = symbol.parent.valueDeclaration; - return resolveName(secondaryLocation, name.escapedText, meaning, undefined, name, true); - } + function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, undefined, name, true); } } } + function getJSSpecialAssignmentLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getSpecialPropertyAssignmentKind(host.expression) === 3) { + var symbol = getSymbolOfNode(host.expression.left); + return symbol && symbol.parent.valueDeclaration; + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -24032,7 +24491,7 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -24043,6 +24502,21 @@ var ts; return undefined; } if (moduleNotFoundError) { + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts", ".tsx"]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } if (resolutionDiagnostic) { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } @@ -24439,7 +24913,7 @@ var ts; return access.accessibility === 0; } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { + if (symbol && enclosingDeclaration) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { @@ -24455,6 +24929,13 @@ var ts; } return hasAccessibleDeclarations; } + else { + if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + return { + accessibility: 0 + }; + } + } meaningToLook = getQualifiedLeftMeaning(meaning); symbol = getParentOfSymbol(symbol); } @@ -24502,6 +24983,11 @@ var ts; isDeclarationVisible(declaration.parent.parent.parent)) { return addVisibleAlias(declaration, declaration.parent.parent); } + else if (ts.isLateVisibilityPaintedStatement(declaration) + && !ts.hasModifier(declaration, 1) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } return false; } return true; @@ -24659,7 +25145,7 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined, + visitedSymbols: undefined, inferTypeParameters: undefined }; } @@ -24751,15 +25237,24 @@ var ts; } if (type.flags & 32768 || objectFlags & 3) { if (type.flags & 32768 && ts.contains(context.inferTypeParameters, type)) { - return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, undefined)); + } + if (context.flags & 4 && + type.flags & 32768 && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8), undefined); } var name = type.symbol ? symbolToName(type.symbol, context, 67901928, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { - var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name, typeArgumentNodes); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67901928, typeArgumentNodes); } if (type.flags & (131072 | 262144)) { var types = type.flags & 131072 ? formatUnionTypes(type.types) : type.types; @@ -24807,14 +25302,24 @@ var ts; ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { var symbol = type.symbol; + var id; if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); if (isJavaScriptConstructor(symbol.valueDeclaration)) { var isInstanceType = type === getInferredClassType(symbol) ? 67901928 : 67216319; return symbolToTypeNode(symbol, context, isInstanceType); @@ -24824,7 +25329,7 @@ var ts; shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, 67216319); } - else if (ts.contains(context.symbolStack, symbol)) { + else if (context.visitedSymbols && context.visitedSymbols.has(id)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { return symbolToTypeNode(typeAlias, context, 67901928); @@ -24834,19 +25339,13 @@ var ts; } } else { - if (!context.symbolStack) { - context.symbolStack = []; - } - var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; - if (isConstructorObject) { - return createTypeNodeFromObjectType(type); - } - else { - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + if (!context.visitedSymbols) { + context.visitedSymbols = ts.createMap(); } + context.visitedSymbols.set(id, true); + var result = createTypeNodeFromObjectType(type); + context.visitedSymbols.delete(id); + return result; } } else { @@ -24861,7 +25360,7 @@ var ts; return declaration.parent.kind === 273 || declaration.parent.kind === 239; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return (!!(context.flags & 4096) || ts.contains(context.symbolStack, symbol)) && + return (!!(context.flags & 4096) || (context.visitedSymbols && context.visitedSymbols.has(id))) && (!(context.flags & 8) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); } } @@ -24893,10 +25392,6 @@ var ts; var typeLiteralNode = ts.createTypeLiteralNode(members); return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024) ? 0 : 1); } - function symbolToTypeReferenceName(symbol) { - var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928, false) : ts.createIdentifier(""); - return entityName; - } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { @@ -24929,7 +25424,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = void 0; + var resultType = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -24940,55 +25435,61 @@ var ts; } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); - var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); - var namePart = symbolToTypeReferenceName(parent); - (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); - } - else { - qualifiedName = ts.createQualifiedName(namePart, undefined); - } + var flags_2 = context.flags; + context.flags |= 16; + var ref = symbolToTypeNode(parent, context, 67901928, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } } } - var entityName = void 0; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } var typeArgumentNodes = void 0; if (typeArguments.length > 0) { var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } - if (typeArgumentNodes) { - var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; - lastIdentifier.typeArguments = undefined; - } - return ts.createTypeReferenceNode(entityName, typeArgumentNodes); + var flags = context.flags; + context.flags |= 16; + var finalRef = symbolToTypeNode(type.symbol, context, 67901928, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } } - function addToQualifiedNameMissingRightIdentifier(left, right) { - ts.Debug.assert(left.right === undefined); - if (right.kind === 71) { - left.right = right; - return left; + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; } - var rightPart = right; - while (rightPart.left.kind !== 71) { - rightPart = rightPart.left; + else { + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; } - left.right = rightPart.left; - rightPart.left = left; - return right; + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; @@ -25126,32 +25627,47 @@ var ts; } return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928, undefined, type.symbol.escapedName, false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; context.flags &= ~512; - var name = symbolToName(type.symbol, context, 67901928, true); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var shouldUseGeneratedName = context.flags & 4 && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8) + : symbolToName(type.symbol, context, 67901928, true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148); - ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 292); + } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; + var dotDotDotToken = isRest ? ts.createToken(24) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : - cloneBindingName(parameterDeclaration.name) : + parameterDeclaration.name.kind === 71 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + parameterDeclaration.name.kind === 145 ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216) : + cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; @@ -25169,7 +25685,7 @@ var ts; } } } - function lookupSymbolChain(symbol, context, meaning) { + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; var isTypeParameter = symbol.flags & 262144; @@ -25199,7 +25715,7 @@ var ts; return accessibleSymbolChain; } if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && !(symbol.flags & (2048 | 4096))) { return [symbol]; } @@ -25230,21 +25746,50 @@ var ts; } return typeParameterNodes; } - function symbolToTypeNode(symbol, context, meaning) { - var chain = lookupSymbolChain(symbol, context, meaning); + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384)); context.flags |= 16777216; var rootName = getNameOfSymbolAsWritten(chain[0], context); context.flags ^= 16777216; var isTypeOf = meaning === 67216319; if (ambientModuleSymbolRegex.test(rootName)) { - var nonRootParts = chain.length > 1 ? createEntityNameFromSymbolChain(chain, chain.length - 1, 1) : undefined; - var typeParameterNodes = lookupTypeParameterNodes(chain, 0, context); - return ts.createImportTypeNode(ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))), nonRootParts, typeParameterNodes, isTypeOf); + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))); + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } } - var entityName = createEntityNameFromSymbolChain(chain, chain.length - 1, 0); - return isTypeOf ? ts.createTypeQueryNode(entityName) : ts.createTypeReferenceNode(entityName, undefined); - function createEntityNameFromSymbolChain(chain, index, stopper) { - var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; if (index === 0) { context.flags |= 16777216; @@ -25253,9 +25798,26 @@ var ts; if (index === 0) { context.flags ^= 16777216; } + var parent = chain[index - 1]; + if (!(context.flags & 16) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); identifier.symbol = symbol; - return index > stopper ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1, stopper), identifier) : identifier; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; } } function symbolToName(symbol, context, meaning, expectsIdentifier) { @@ -25394,6 +25956,23 @@ var ts; return "default"; } if (symbol.declarations && symbol.declarations.length) { + if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { + var file = ts.getDeclarationOfKind(symbol, 273); + if (!file || !context.tracker.moduleResolverHost) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl); + } + } + } + } + else { + return "\"" + ts.getResolvedExternalModuleName(context.tracker.moduleResolverHost, file, ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration))) + "\""; + } + } var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { @@ -25435,6 +26014,9 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { + case 291: + case 296: + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); case 181: return isDeclarationVisible(node.parent.parent); case 231: @@ -26048,6 +26630,10 @@ var ts; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } if (declaration.kind === 248) { return links.type = checkExpression(declaration.expression); } @@ -26062,7 +26648,7 @@ var ts; declaration.kind === 184 && declaration.parent.kind === 199) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else if (ts.isJSDocPropertyTag(declaration) + else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) || ts.isIdentifier(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) @@ -26317,12 +26903,14 @@ var ts; case 152: case 162: case 163: - case 281: + case 283: case 233: case 153: case 191: case 192: case 236: + case 295: + case 296: case 291: case 176: case 170: @@ -26333,7 +26921,7 @@ var ts; else if (node.kind === 170) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 234 || node.kind === 204 || node.kind === 235) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; @@ -26349,13 +26937,12 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 235 || node.kind === 234 || - node.kind === 204 || node.kind === 236) { + if (node.kind === 235 || + node.kind === 234 || + node.kind === 204 || + ts.isTypeAlias(node)) { var declaration = node; - var typeParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - if (typeParameters) { - result = appendTypeParameters(result, typeParameters); - } + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); } } return result; @@ -26589,9 +27176,9 @@ var ts; return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 292 || d.kind === 236; + return ts.isJSDocTypeAlias(d) || d.kind === 236; }); - var typeNode = declaration.kind === 292 ? declaration.typeExpression : declaration.type; + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -26778,7 +27365,7 @@ var ts; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); return (node.kind === 154 || (returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && - (!typeParameters || typeParameters.every(isThislessTypeParameter)); + typeParameters.every(isThislessTypeParameter); } function isThisless(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { @@ -26818,6 +27405,8 @@ var ts; var symbol = type.symbol; var members = getMembersOfSymbol(symbol); type.declaredProperties = getNamedMembers(members); + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call")); type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new")); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); @@ -26883,9 +27472,9 @@ var ts; var earlySymbol = earlySymbols && earlySymbols.get(memberName); if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_3 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); lateSymbol = createSymbol(0, memberName, 1024); } lateSymbol.nameType = type; @@ -27266,10 +27855,8 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); var templateModifiers = getMappedTypeModifiers(type); - var constraintDeclaration = type.declaration.typeParameter.constraint; var include = keyofStringsOnly ? 32 : 1120; - if (constraintDeclaration.kind === 174 && - constraintDeclaration.operator === 128) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), undefined, prop); @@ -27330,12 +27917,18 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4)), type.mapper || identityMapper) : unknownType); } + function getConstraintDeclarationForMappedType(type) { + return type.declaration.typeParameter.constraint; + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); + return constraintDeclaration.kind === 174 && + constraintDeclaration.operator === 128; + } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 174 && - constraintDeclaration.operator === 128) { - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); } else { var declaredType = getTypeFromMappedTypeNode(type.declaration); @@ -27481,9 +28074,9 @@ var ts; } function getConstraintOfDistributiveConditionalType(type) { if (type.root.isDistributive) { - var constraint = getConstraintOfType(type.checkType); + var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); if (constraint) { - var mapper = createTypeMapper([type.root.checkType], [constraint]); + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 16384)) { return instantiated; @@ -27810,9 +28403,10 @@ var ts; } function getTypeParametersFromDeclaration(declaration) { var result; - ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); - }); + } return result; } function symbolsToArray(symbols) { @@ -27825,10 +28419,10 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 280 + return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 282 || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 280; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -27839,7 +28433,7 @@ var ts; return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -27856,6 +28450,13 @@ var ts; } return false; } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282; + } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); @@ -27897,7 +28498,7 @@ var ts; for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); @@ -27925,6 +28526,7 @@ var ts; for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319, undefined, undefined, false); paramSymbol = resolvedSymbol; @@ -27936,11 +28538,12 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 177) { + if (type && type.kind === 177) { hasLiteralTypes = true; } - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || isUntypedSignatureInJSFile || isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { @@ -27967,7 +28570,7 @@ var ts; return links.resolvedSignature; } function maybeAddJsSyntheticRestParameter(declaration, parameters) { - if (!containsArgumentsReference(declaration)) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { return false; } var lastParam = ts.lastOrUndefined(declaration.parameters); @@ -28326,7 +28929,7 @@ var ts; var isJs = ts.isInJavaScriptFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 286; + var missingAugmentsTag = isJs && node.parent.kind !== 289; var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -28458,7 +29061,7 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node)) { + while (node && !ts.isStatement(node) && node.kind !== 285) { var parent = node.parent; if (parent.kind === 170 && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); @@ -28870,7 +29473,7 @@ var ts; includes & 4096 ? includes & 16777216 ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 8374815 ? 0 : 268435456, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -28904,7 +29507,7 @@ var ts; ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex : !ts.isIdentifierTypePredicate(b); } - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -28915,7 +29518,7 @@ var ts; var type = unionTypes.get(id); if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, 12288); - type = createType(131072 | propagatedFlags); + type = createType(131072 | propagatedFlags | unionOfUnitTypes); unionTypes.set(id, type); type.types = types; type.aliasSymbol = aliasSymbol; @@ -28926,7 +29529,8 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -28973,6 +29577,28 @@ var ts; } } } + function intersectUnionsOfUnitTypes(types) { + var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 268435456) !== 0; }); + var unionType = types[unionIndex]; + var intersection = unionType.types; + var i = types.length - 1; + var _loop_5 = function () { + var t = types[i]; + if (t.flags & 268435456) { + intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + ts.orderedRemoveItemAt(types, i); + } + i--; + }; + while (i > unionIndex) { + _loop_5(); + } + if (intersection === unionType.types) { + return false; + } + types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 268435456); + return true; + } function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return emptyObjectType; @@ -28997,6 +29623,9 @@ var ts; return typeSet[0]; } if (includes & 131072) { + if (includes & 268435456 && intersectUnionsOfUnitTypes(typeSet)) { + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 131072) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1, aliasSymbol, aliasTypeArguments); @@ -29016,7 +29645,8 @@ var ts; function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -29189,6 +29819,10 @@ var ts; return type.flags & 1048576 ? getSimplifiedIndexedAccessType(type) : type; } function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; var objectType = type.objectType; if (objectType.flags & 262144 && isGenericObjectType(objectType)) { if (ts.some(objectType.types, isStringIndexOnlyType)) { @@ -29203,26 +29837,26 @@ var ts; regularTypes.push(t); } } - return getUnionType([ + return type.simplified = getUnionType([ getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), getIntersectionType(stringIndexTypes) ]); } if (ts.some(objectType.types, isMappedTypeToNever)) { var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); } } if (isGenericMappedType(objectType)) { - return substituteIndexedMappedType(objectType, type); + return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 32768) { var constraint = getConstraintFromTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { - return substituteIndexedMappedType(constraint, type); + return type.simplified = substituteIndexedMappedType(constraint, type); } } - return type; + return type.simplified = type; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); @@ -29278,7 +29912,7 @@ var ts; var type = createObjectType(32, node.symbol); type.declaration = node; type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); links.resolvedType = type; getConstraintTypeFromMappedType(type); } @@ -29360,7 +29994,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var checkType = getTypeFromTypeNode(node.checkType); - var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); var allOuterTypeParameters = getOuterTypeParameters(node, true); var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); var root = { @@ -29373,7 +30008,7 @@ var ts; inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, - aliasSymbol: getAliasSymbolForTypeNode(node), + aliasSymbol: aliasSymbol, aliasTypeArguments: aliasTypeArguments }; links.resolvedType = getConditionalType(root, undefined); @@ -29470,7 +30105,7 @@ var ts; else { var type = createObjectType(16, node.symbol); type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { type = createArrayType(type); } @@ -29480,10 +30115,9 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 236 ? getSymbolOfNode(node.parent) : undefined; + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); + function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } function getSpreadType(left, right, symbol, typeFlags, objectFlags) { @@ -29651,8 +30285,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119: - case 276: - case 277: + case 278: + case 279: return anyType; case 137: return stringType; @@ -29693,21 +30327,22 @@ var ts; return getTypeFromUnionTypeNode(node); case 169: return getTypeFromIntersectionTypeNode(node); - case 278: - return getTypeFromJSDocNullableTypeNode(node); case 280: + return getTypeFromJSDocNullableTypeNode(node); + case 282: return addOptionality(getTypeFromTypeNode(node.type)); case 172: - case 279: - case 275: + case 281: + case 277: return getTypeFromTypeNode(node.type); - case 282: + case 284: return getTypeFromJSDocVariadicType(node); case 162: case 163: case 165: - case 284: - case 281: + case 286: + case 283: + case 287: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 174: return getTypeFromTypeOperatorNode(node); @@ -29872,6 +30507,15 @@ var ts; var typeParameters = links.outerTypeParameters; if (!typeParameters) { var declaration_1 = symbol.declarations[0]; + if (ts.isInJavaScriptFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } var outerTypeParameters = getOuterTypeParameters(declaration_1, true); if (isJavaScriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); @@ -29907,8 +30551,8 @@ var ts; } function isTypeParameterPossiblyReferenced(tp, node) { if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_2 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 212 ? "quit" : n === container_2; })) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 212 ? "quit" : n === container_3; })) { return ts.forEachChild(node, containsReference); } } @@ -30636,7 +31280,7 @@ var ts; if (discriminant) { return hasExcessProperties(source, discriminant, undefined, reportErrors); } - var _loop_5 = function (prop) { + var _loop_6 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { ts.Debug.assert(!!errorNode); @@ -30667,7 +31311,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_5(prop); + var state_3 = _loop_6(prop); if (typeof state_3 === "object") return state_3.value; } @@ -30941,15 +31585,18 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || constraint.flags & 1) { + if (!constraint || (source.flags & 32768 && constraint.flags & 1)) { if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~134217728))) { errorInfo = saveErrorInfo; return result; } } - else if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var instantiated = getTypeWithThisArgument(constraint, source); + if (result = isRelatedTo(instantiated, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else if (source.flags & 524288) { @@ -31045,10 +31692,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_1; - if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -32910,7 +33557,7 @@ var ts; if (type.flags & 131072) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 268435456); } return f(type) ? type : neverType; } @@ -33948,7 +34595,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 281) { + if (jsdocType && jsdocType.kind === 283) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -34280,7 +34927,7 @@ var ts; case 54: var type = getContextualType(binaryExpression); return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? - getTypeOfExpression(left, true) : type; + getTypeOfExpression(left) : type; case 53: case 26: return node === right ? getContextualType(binaryExpression) : undefined; @@ -34507,8 +35154,18 @@ var ts; return unknownType; } } - if (context.typeArguments) { - signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + var links = getNodeLinks(context); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(valueType); + var cachedResolved = links.resolvedSignatures.get(cacheKey); + if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { + signatures = cachedResolved; + } + else if (!cachedResolved) { + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); } return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0); } @@ -34758,7 +35415,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 179 || contextualType.pattern.kind === 183); - var isInJSFile = ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; @@ -35249,6 +35906,33 @@ var ts; } return undefined; } + function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { + var links = getNodeLinks(openingLikeElement); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(elementType); + if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { + return; + } + else if (links.resolvedSignatures.get(cacheKey)) { + return links.resolvedSignatures.get(cacheKey); + } + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + var signatures = getSignaturesOfType(elementType, 1); + if (signatures.length === 0) { + signatures = getSignaturesOfType(elementType, 0); + if (signatures.length === 0) { + if (reportErrors) { + error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); + } + return; + } + } + var results = instantiateJsxSignatures(openingLikeElement, signatures); + links.resolvedSignatures.set(cacheKey, results); + return results; + } function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType.flags & 131072) { var types = elementType.types; @@ -35278,15 +35962,10 @@ var ts; } return anyType; } - var signatures = getSignaturesOfType(elementType, 1); - if (signatures.length === 0) { - signatures = getSignaturesOfType(elementType, 0); - if (signatures.length === 0) { - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - return unknownType; - } + var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, true); + if (!ts.length(instantiatedSignatures)) { + return unknownType; } - var instantiatedSignatures = instantiateJsxSignatures(openingLikeElement, signatures); var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : @@ -35436,7 +36115,7 @@ var ts; else if (!isSourceAttributeTypeAssignableToTarget) { if (ts.length(openingLikeElement.attributes.properties)) { var reportedError = false; - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (ts.isJsxSpreadAttribute(prop)) return "continue"; var name = ts.idText(prop.name); @@ -35449,7 +36128,7 @@ var ts; }; for (var _b = 0, _c = openingLikeElement.attributes.properties; _b < _c.length; _b++) { var prop = _c[_b]; - _loop_6(prop); + _loop_7(prop); } if (reportedError) { return; @@ -36418,9 +37097,9 @@ var ts; var isDecorator = node.kind === 149; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; - if (!isDecorator && !isJsxOpeningOrSelfClosingElement) { + if (!isDecorator) { typeArguments = node.typeArguments; - if (isTaggedTemplate || node.expression.kind !== 97) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97) { ts.forEach(typeArguments, checkSourceElement); } } @@ -36809,18 +37488,6 @@ var ts; } function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { ts.Debug.assert(!(elementType.flags & 131072)); - return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - } - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - if (elementType.flags & 131072) { - var types = elementType.types; - var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); - } - return result; - } var callSignatures = elementType && getSignaturesOfType(elementType, 0); if (callSignatures && callSignatures.length > 0) { return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); @@ -36839,7 +37506,18 @@ var ts; return resolveDecorator(node, candidatesOutArray); case 256: case 255: - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; + var exprTypes = checkExpression(node.tagName); + return forEachType(exprTypes, function (exprType) { + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + if (sfcResult && sfcResult !== unknownSignature) { + return sfcResult; + } + var sigs = getInstantiatedJsxSignatures(node, exprType); + if (candidatesOutArray && ts.length(sigs)) { + candidatesOutArray.push.apply(candidatesOutArray, sigs); + } + return ts.length(sigs) ? sigs[0] : unknownSignature; + }) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -37409,7 +38087,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -37611,8 +38289,8 @@ var ts; } if (type.flags & 393216) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -38578,7 +39256,7 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (node.kind !== 159 && node.kind !== 281) { + if (node.kind !== 159 && node.kind !== 283) { registerForUnusedIdentifiersCheck(node); } } @@ -38991,7 +39669,7 @@ var ts; n.parent.kind !== 234 && n.parent.kind !== 204 && n.flags & 4194304) { - if (!(flags & 2)) { + if (!(flags & 2) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { flags |= 1; } flags |= 2; @@ -39228,7 +39906,8 @@ var ts; switch (d.kind) { case 235: case 236: - case 292: + case 296: + case 291: return 2; case 238: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 @@ -39247,10 +39926,10 @@ var ts; case 242: case 245: case 244: - var result_2 = 0; + var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; case 231: case 181: case 233: @@ -39557,7 +40236,7 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDocTypedefTag(node) { + function checkJSDocTypeAliasTag(node) { if (!node.typeExpression) { error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } @@ -39655,7 +40334,13 @@ var ts; } } function registerForUnusedIdentifiersCheck(node) { - if (potentiallyUnusedIdentifiers) { + if (produceDiagnostics) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } potentiallyUnusedIdentifiers.push(node); } } @@ -39663,10 +40348,6 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 273: - case 238: - checkUnusedModuleMembers(node, addDiagnostic); - break; case 234: case 204: checkUnusedClassMembers(node, addDiagnostic); @@ -39675,6 +40356,8 @@ var ts; case 235: checkUnusedTypeParameters(node, addDiagnostic); break; + case 273: + case 238: case 212: case 240: case 219: @@ -39707,31 +40390,6 @@ var ts; } } } - function checkUnusedLocalsAndParameters(node, addDiagnostic) { - if (!(node.flags & 4194304)) { - node.locals.forEach(function (local) { - if (local.flags & 262144 ? (local.flags & 3 && !(local.isReferenced & 3)) : !local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148) { - var parameter = ts.getRootDeclaration(local.valueDeclaration); - var name = ts.getNameOfDeclaration(local.valueDeclaration); - if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - addDiagnostic(1, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } - } - else { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local), addDiagnostic); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { @@ -39741,10 +40399,8 @@ var ts; return; } } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); - } + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(0, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -39788,7 +40444,7 @@ var ts; } function checkUnusedTypeParameters(node, addDiagnostic) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304) && typeParameters && ts.last(getSymbolOfNode(node).declarations) === node) { + if (!(node.flags & 4194304) && ts.last(getSymbolOfNode(node).declarations) === node) { for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { @@ -39797,49 +40453,87 @@ var ts; } } } - function checkUnusedModuleMembers(node, addDiagnostic) { - if (!(node.flags & 4194304)) { - var unusedImports_1 = ts.createMap(); - node.locals.forEach(function (local) { - if (local.isReferenced || local.exportSymbol) - return; - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isAmbientModule(declaration)) - continue; - if (isImportedDeclaration(declaration)) { - var importClause = importClauseFromImported(declaration); - var key = String(getNodeId(importClause)); - var group_1 = unusedImports_1.get(key); - if (group_1) { - group_1[1].push(declaration); - } - else { - unusedImports_1.set(key, [importClause, [declaration]]); + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304) + return; + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + if (local.flags & 262144 ? !(local.flags & 3 && !(local.isReferenced & 3)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + if (parameter) { + var name = ts.getNameOfDeclaration(local.valueDeclaration); + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { + addDiagnostic(1, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); } } - }); - unusedImports_1.forEach(function (_a) { - var importClause = _a[0], unuseds = _a[1]; - var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { - for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { - var unused = unuseds_1[_i]; - errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); - } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } - else if (unuseds.length === 1) { - addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else if (unuseds.length === 1) { + addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else { + addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 : 0; + if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } - else { - addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl))); - } - }); - } + } + else if (bindingElements.length === 1) { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + } + else { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + }); } function isImportedDeclaration(node) { return node.kind === 244 || node.kind === 247 || node.kind === 245; @@ -40759,7 +41453,7 @@ var ts; for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { var declaration = declarations_6[_i]; var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - var numTypeParameters = ts.length(sourceParameters); + var numTypeParameters = sourceParameters.length; if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; } @@ -40894,7 +41588,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -40912,7 +41606,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -41766,26 +42460,27 @@ var ts; return checkInferType(node); case 178: return checkImportType(node); - case 286: + case 289: return checkJSDocAugmentsTag(node); + case 296: + case 291: + return checkJSDocTypeAliasTag(node); case 292: - return checkJSDocTypedefTag(node); - case 288: return checkJSDocParameterTag(node); - case 281: + case 283: checkSignatureDeclaration(node); - case 279: + case 281: + case 280: case 278: - case 276: - case 277: - case 284: + case 279: + case 286: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 282: + case 284: checkJSDocVariadicType(node); return; - case 275: + case 277: return checkSourceElement(node.type); case 175: return checkIndexedAccessType(node); @@ -41894,9 +42589,9 @@ var ts; var parent = node.parent; var paramTag = parent.parent; if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { - var host_2 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_2) { - var lastParamDeclaration = ts.lastOrUndefined(host_2.parameters); + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -41950,6 +42645,9 @@ var ts; return ts.Debug.assertNever(kind); } } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { @@ -41960,25 +42658,19 @@ var ts; ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); deferredNodes = []; - if (produceDiagnostics) { - ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName)); - allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []); - } ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { if (unusedIsError(kind)) { diagnostics.add(diag); } }); } deferredNodes = undefined; - seenPotentiallyUnusedIdentifiers.clear(); - potentiallyUnusedIdentifiers = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -42236,10 +42928,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 288) { + if (entityName.parent.kind === 292) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 147 && entityName.parent.parent.kind === 291) { + if (entityName.parent.kind === 147 && entityName.parent.parent.kind === 295) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -42677,6 +43369,7 @@ var ts; function isRequiredInitializedParameter(parameter) { return strictNullChecks && !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && parameter.initializer && !ts.hasModifier(parameter, 92); } @@ -42914,7 +43607,22 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024); }, - getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); + var otherKind = accessor.kind === 156 ? 155 : 156; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 156 ? accessor : otherAccessor; + var getAccessor = accessor.kind === 155 ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 206 && node.parent.parent && node.parent.parent.kind === 267; @@ -43438,7 +44146,7 @@ var ts; } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(ts.getEffectiveTypeParameterDeclarations(node), file); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { if (!ts.isArrowFunction(node)) { @@ -44075,8 +44783,8 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + if (ts.isNodeArray(typeParameters)) { + var pos = typeParameters.pos, end = typeParameters.end; return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } @@ -44201,7 +44909,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -44270,10 +44978,8 @@ var ts; if (!elements || elements === ts.emptyArray) { elements = []; } - else { - if (ts.isNodeArray(elements)) { - return elements; - } + else if (ts.isNodeArray(elements)) { + return elements; } var array = elements; array.pos = -1; @@ -44326,6 +45032,13 @@ var ts; node.text = text; return node; } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(12); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; function createLiteralFromNode(sourceNode) { var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; @@ -44359,7 +45072,7 @@ var ts; recordTempVariable(name); } if (reservedInNestedScopes) { - name.autoGenerateFlags |= 16; + name.autoGenerateFlags |= 8; } return name; } @@ -44382,7 +45095,7 @@ var ts; ts.createUniqueName = createUniqueName; function createOptimisticUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateFlags = 3 | 32; + name.autoGenerateFlags = 3 | 16; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -44390,18 +45103,15 @@ var ts; ts.createOptimisticUniqueName = createOptimisticUniqueName; function createFileLevelUniqueName(text) { var name = createOptimisticUniqueName(text); - name.autoGenerateFlags |= 64; + name.autoGenerateFlags |= 32; return name; } ts.createFileLevelUniqueName = createFileLevelUniqueName; - function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { - var name = createIdentifier(""); - name.autoGenerateFlags = 4; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 | flags; name.autoGenerateId = nextAutoGenerateId; name.original = node; - if (shouldSkipNameGenerationScope) { - name.autoGenerateFlags |= 8; - } nextAutoGenerateId++; return name; } @@ -44488,7 +45198,7 @@ var ts; ts.updateQualifiedName = updateQualifiedName; function parenthesizeForComputedName(expression) { return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26) || - expression.kind === 297 ? + expression.kind === 301 ? createParen(expression) : expression; } @@ -45528,6 +46238,12 @@ var ts; return block; } ts.createBlock = createBlock; + function createExpressionStatement(expression) { + var node = createSynthesizedNode(215); + node.expression = expression; + return node; + } + ts.createExpressionStatement = createExpressionStatement; function updateBlock(node, statements) { return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) @@ -45554,9 +46270,7 @@ var ts; } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(215); - node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); - return node; + return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression)); } ts.createStatement = createStatement; function updateStatement(node, expression) { @@ -46436,28 +47150,28 @@ var ts; } ts.getMutableClone = getMutableClone; function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295); + var node = createSynthesizedNode(299); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299); + var node = createSynthesizedNode(303); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(302); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296); + var node = createSynthesizedNode(300); node.expression = expression; node.original = original; setTextRange(node, original); @@ -46473,7 +47187,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297) { + if (node.kind === 301) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { @@ -46483,7 +47197,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(301); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -46494,15 +47208,31 @@ var ts; : node; } ts.updateCommaList = updateCommaList; - function createBundle(sourceFiles) { + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } var node = ts.createNode(274); + node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; - function updateBundle(node, sourceFiles) { - if (node.sourceFiles !== sourceFiles) { - return createBundle(sourceFiles); + function createUnparsedSourceFile(text) { + var node = ts.createNode(275); + node.text = text; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration) { + var node = ts.createNode(276); + node.javascriptText = javascript; + node.declarationText = declaration; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); } return node; } @@ -46704,6 +47434,15 @@ var ts; return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); } ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; function getConstantValue(node) { var emitNode = node.emitNode; return emitNode && emitNode.constantValue; @@ -47425,7 +48164,7 @@ var ts; function parenthesizeSubexpressionOfConditionalExpression(e) { var emittedExpression = ts.skipPartiallyEmittedExpressions(e); return emittedExpression.kind === 199 && emittedExpression.operatorToken.kind === 26 || - emittedExpression.kind === 297 + emittedExpression.kind === 301 ? ts.createParen(e) : e; } @@ -47434,7 +48173,7 @@ var ts; var check = ts.skipPartiallyEmittedExpressions(e); return (check.kind === 204 || check.kind === 191 || - check.kind === 297 || + check.kind === 301 || ts.isBinaryExpression(check) && check.operatorToken.kind === 26) ? ts.createParen(e) : e; @@ -47537,6 +48276,7 @@ var ts; switch (member.kind) { case 164: case 174: + case 171: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -47579,7 +48319,7 @@ var ts; case 184: node = node.expression; continue; - case 296: + case 300: node = node.expression; continue; } @@ -47609,7 +48349,7 @@ var ts; case 207: case 208: return (kinds & 2) !== 0; - case 296: + case 300: return (kinds & 4) !== 0; } return false; @@ -47646,7 +48386,7 @@ var ts; case 189: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 207: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 208: return ts.updateNonNullExpression(outerExpression, expression); - case 296: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 300: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } function isIgnorableParen(node) { @@ -47994,7 +48734,7 @@ var ts; statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements); } var declarations = context.endLexicalEnvironment(); - return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); } ts.visitLexicalEnvironment = visitLexicalEnvironment; function visitParameterList(nodes, visitor, context, nodesVisitor) { @@ -48271,9 +49011,9 @@ var ts; return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); case 273: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 296: + case 300: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297: + case 301: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -48311,7 +49051,7 @@ var ts; case 214: case 205: case 230: - case 295: + case 299: break; case 145: result = reduceNode(node.left, cbNode, result); @@ -48674,10 +49414,10 @@ var ts; case 273: result = reduceNodes(node.statements, cbNodes, result); break; - case 296: + case 300: result = reduceNode(node.expression, cbNode, result); break; - case 297: + case 301: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -48691,8 +49431,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements) - : ts.addRange(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + : ts.prependRange(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function liftToBlock(nodes) { @@ -48812,16 +49552,6 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; - function getNamedImportCount(node) { - if (!(node.importClause && node.importClause.namedBindings)) - return 0; - var names = node.importClause.namedBindings; - if (!names) - return 0; - if (!ts.isNamedImports(names)) - return 0; - return names.elements.length; - } function containsDefaultReference(node) { if (!node) return false; @@ -48832,12 +49562,38 @@ var ts; function isNamedDefaultReference(e) { return e.propertyName && e.propertyName.escapedText === "default"; } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 273 ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; function getImportNeedsImportStarHelper(node) { - return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); } ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { - return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -49402,7 +50158,21 @@ var ts; var classAliases; var applicableSubstitutions; var pendingExpressions; - return transformSourceFile; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 274) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276) { + return ts.createUnparsedSourceFile(prepend.javascriptText); + } + return prepend; + })); + } function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -49714,7 +50484,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.addRange(statements, context.endLexicalEnvironment()); + ts.prependRange(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ @@ -49790,7 +50560,7 @@ var ts; if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); var alias = ts.getSynthesizedClone(temp); - alias.autoGenerateFlags &= ~16; + alias.autoGenerateFlags &= ~8; classAliases[ts.getOriginalNodeId(node)] = alias; } ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); @@ -49917,7 +50687,7 @@ var ts; } function transformInitializedProperty(property, receiver) { var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) - ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32))) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); @@ -50536,6 +51306,9 @@ var ts; var innerExpression = ts.skipOuterExpressions(node.expression, ~2); if (ts.isAssertionExpression(innerExpression)) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } return ts.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -50596,8 +51369,9 @@ var ts; currentNamespaceContainerName = localName; var statements = []; startLexicalEnvironment(); - ts.addRange(statements, ts.map(node.members, transformEnumMember)); - ts.addRange(statements, endLexicalEnvironment()); + var members = ts.map(node.members, transformEnumMember); + ts.prependRange(statements, endLexicalEnvironment()); + ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); } @@ -50741,7 +51515,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -51097,7 +51871,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -51311,7 +52085,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); if (languageVersion >= 2) { @@ -51331,7 +52105,7 @@ var ts; var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); } else { result = expression; @@ -51491,7 +52265,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -51568,9 +52342,14 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -51817,7 +52596,7 @@ var ts; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { @@ -51840,11 +52619,11 @@ var ts; statementOffset = ts.addPrologue(statements, body.statements, false, visitor); } ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(undefined, node)); - var trailingStatements = endLexicalEnvironment(); - if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) { + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, true); + ts.prependRange(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); - ts.addRange(statements, trailingStatements); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } return body; @@ -51976,7 +52755,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -51991,7 +52770,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -52001,7 +52780,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -52013,7 +52792,7 @@ var ts; function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -52467,7 +53246,7 @@ var ts; (function (ts) { function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -52613,7 +53392,7 @@ var ts; } var convertedLoopState; var enabledSubstitutions; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -52777,7 +53556,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0, 0); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -52946,7 +53725,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); ts.setEmitFlags(block, 1536); return block; @@ -53009,7 +53788,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, false); } @@ -53405,12 +54184,13 @@ var ts; var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression); ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); ts.setEmitFlags(returnStatement, 384 | 32 | 1024); statements.push(returnStatement); closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); + ts.prependRange(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, false); if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { multiLine = true; @@ -53815,7 +54595,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1, statements_4); } - ts.addRange(statements_4, lexicalEnvironment); + ts.prependRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, true); } if (ts.isBlock(loopBody)) { @@ -54132,8 +54912,10 @@ var ts; } function visitTypeScriptClassWrapper(node) { var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); - var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); - var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); var variable = varStatement.declarationList.declarations[0]; var initializer = ts.skipOuterExpressions(variable.initializer); @@ -54528,7 +55310,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.enableSubstitution(184); context.enableSubstitution(269); - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { return node; } @@ -54668,7 +55450,7 @@ var ts; var exceptionBlockStack; var currentExceptionBlock; var withBlockStack; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; @@ -54852,7 +55634,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); inGeneratorFunctionBody = savedInGeneratorFunctionBody; inStatementContainingYield = savedInStatementContainingYield; @@ -56286,7 +57068,7 @@ var ts; var currentModuleInfo; var noSubstitution; var needUMDDynamicImportHelper; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { return node; @@ -56318,7 +57100,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, false); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); @@ -56433,7 +57215,7 @@ var ts; } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); @@ -56445,7 +57227,7 @@ var ts; } function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); if (expressionResult) { if (emitAsReturn) { var statement = ts.createReturn(expressionResult); @@ -56478,27 +57260,82 @@ var ts; return visitFunctionDeclaration(node); case 234: return visitClassDeclaration(node); - case 298: + case 302: return visitMergeDeclarationMarker(node); - case 299: + case 303: return visitEndOfDeclarationMarker(node); default: - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } - function importCallExpressionVisitor(node) { - if (!(node.transformFlags & 67108864)) { + function moduleExpressionElementVisitor(node) { + if (!(node.transformFlags & 67108864) && !(node.transformFlags & 2048)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } + else if (node.transformFlags & 1024 && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } else { - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 269: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 270: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 271: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 153: + case 155: + case 156: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0, false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } function visitImportCallExpression(node) { - var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); var containsLexicalThis = !!(node.transformFlags & 16384); switch (compilerOptions.module) { case ts.ModuleKind.AMD: @@ -56682,20 +57519,20 @@ var ts; var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), node, true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), node, true); } return ts.singleOrMany(statements); } function visitFunctionDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), node), node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -56709,10 +57546,10 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -56749,7 +57586,7 @@ var ts; } } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -56760,12 +57597,25 @@ var ts; } return ts.singleOrMany(statements); } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + ts.setEmitFlags(expression, 4); + expression = createExportExpression(exportName, expression, location); + } + return expression; + } + return ts.createAssignment(name, value); + } function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), undefined, context, 0, false, createExportExpression); + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), undefined, context, 0, false, createAllExportExpressions); } else { - return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); } } function visitMergeDeclarationMarker(node) { @@ -56997,8 +57847,8 @@ var ts; var exportedNames = getExports(node.left); if (exportedNames) { var expression = node; - for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { - var exportName = exportedNames_1[_i]; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression, node); } @@ -57018,8 +57868,8 @@ var ts; var expression = node.kind === 198 ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 ? 59 : 60), ts.createLiteral(1)), node) : node; - for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { - var exportName = exportedNames_2[_i]; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); } @@ -57095,7 +57945,7 @@ var ts; var hoistedStatements; var enclosingBlockScopedContainer; var noSubstitution; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { return node; @@ -57169,7 +58019,7 @@ var ts; ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); ts.addRange(statements, hoistedStatements); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -57253,11 +58103,11 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_2 = dependencyGroups_1[_i]; - var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var group_1 = dependencyGroups_1[_i]; + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -57616,9 +58466,9 @@ var ts; return visitCatchClause(node); case 212: return visitBlock(node); - case 298: + case 302: return visitMergeDeclarationMarker(node); - case 299: + case 303: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -57869,8 +58719,8 @@ var ts; var exportedNames = getExports(node.left); if (exportedNames) { var expression = node; - for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { - var exportName = exportedNames_3[_i]; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } return expression; @@ -57889,8 +58739,8 @@ var ts; var expression = node.kind === 198 ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; - for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { - var exportName = exportedNames_4[_i]; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } if (node.kind === 198) { @@ -57941,7 +58791,7 @@ var ts; context.enableEmitNotification(273); context.enableSubstitution(71); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -58405,7 +59255,12 @@ var ts; return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - var declarationEmitNodeBuilderFlags = 1024 | 2048 | 4096 | 8 | 524288; + var declarationEmitNodeBuilderFlags = 1024 | + 2048 | + 4096 | + 8 | + 524288 | + 4; function transformDeclarations(context) { var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; var getSymbolAccessibilityDiagnostic = throwDiagnostic; @@ -58419,19 +59274,22 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, - reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, }; var errorNameNode; var currentSourceFile; + var refs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); var noResolve = options.noResolve, stripInternal = options.stripInternal; - var host = context.getEmitHost(); return transformRoot; function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { if (!typeReferenceDirectives) { @@ -58443,6 +59301,10 @@ var ts; necessaryTypeRefernces.set(ref, true); } } + function trackReferencedAmbientModule(node) { + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } function handleSymbolAccessibilityError(symbolAccessibilityResult) { if (symbolAccessibilityResult.accessibility === 0) { if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { @@ -58470,6 +59332,8 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144) + return; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } @@ -58513,12 +59377,16 @@ var ts; resultHasExternalModuleIndicator = false; needsDeclare = false; var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], true, [], [], false); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], true, [], [], false); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - return ts.updateSourceFileNode(sourceFile, filterCandidateImports(updated), true, [], [], false); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), true, [], [], false); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276) { + return ts.createUnparsedSourceFile(prepend.declarationText); + } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); @@ -58540,13 +59408,13 @@ var ts; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); necessaryTypeRefernces = undefined; - var refs = collectReferences(currentSourceFile, ts.createMap()); + refs = collectReferences(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); - refs.forEach(referenceVisitor); var statements = ts.visitNodes(node.statements, visitDeclarationStatements); - var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); @@ -58557,17 +59425,19 @@ var ts; return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { - for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { - var importStatement = emittedImports_1[_i]; - if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { - var expr = importStatement.moduleReference.expression; - if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { return undefined; } } - else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { - return undefined; - } } return { fileName: typeName, pos: -1, end: -1 }; } @@ -58599,7 +59469,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); if (elem) { - ret.set("" + ts.getNodeId(elem), elem); + ret.set("" + ts.getOriginalNodeId(elem), elem); } }); return ret; @@ -58797,58 +59667,42 @@ var ts; return ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } } - function filterCandidateImports(statements) { - var unconsideredStatements = []; + function transformAndReplaceLatePaintedStatements(statements) { while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); - if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { - unconsideredStatements.push(i); - continue; - } if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was foudn which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); - } - switch (i.kind) { - case 242: { - var result = transformImportEqualsDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 243: { - var result = transformImportDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 213: { - var result = transformVariableStatement(i, true); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - default: ts.Debug.assertNever(i, "Unhandled late painted statement!"); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var result = transformTopLevelDeclaration(i, true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } - lateMarkedStatements = unconsideredStatements; return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); - } - function visitLateVisibilityMarkedStatements(statement) { - if (ts.isLateVisibilityPaintedStatement(statement)) { - var key = "" + ts.getNodeId(statement); - if (lateStatementReplacementMap.has(key)) { - var result = lateStatementReplacementMap.get(key); - lateStatementReplacementMap.delete(key); - if (result && ts.isSourceFile(statement.parent) && !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1)) { - needsScopeFixMarker = true; + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; } - return result; } - else { - return ts.getParseTreeNode(statement) ? undefined : statement; - } - } - else { return statement; } } + function isExternalModuleIndicator(result) { + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1) && !ts.isAmbientModule(result); + } function visitDeclarationSubtree(input) { if (shouldStripInternal(input)) return; @@ -59032,11 +59886,20 @@ var ts; return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } - case 242: + } + var result = transformTopLevelDeclaration(input); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 242: { + return transformImportEqualsDeclaration(input); + } case 243: { - lateMarkedStatements = lateMarkedStatements || []; - ts.pushIfUnique(lateMarkedStatements, input); - return input; + return transformImportDeclaration(input); } } if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) @@ -59048,44 +59911,44 @@ var ts; previousEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = input; } - var previousNeedsDeclare; var canProdiceDiagnostic = ts.canProduceDiagnostics(input); var oldDiag = getSymbolAccessibilityDiagnostic; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); } - var oldPossibleImports; + var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 236: - return cleanup(ts.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + return cleanup(ts.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 235: { - return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 233: { - return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); } case 238: { - previousNeedsDeclare = needsDeclare; needsDeclare = false; - oldPossibleImports = lateMarkedStatements; - lateMarkedStatements = undefined; var inner = input.body; if (inner && inner.kind === 239) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); - var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); return cleanup(ts.updateModuleDeclaration(input, undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); needsDeclare = false; - return cleanup(ts.updateModuleDeclaration(input, undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + ts.visitNode(inner, visitDeclarationStatements); + var id = "" + ts.getOriginalNodeId(inner); + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, undefined, mods, input.name, body)); } } case 234: { - var modifiers = ts.createNodeArray(ensureModifiers(input)); + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); var parameterProperties = void 0; @@ -59147,12 +60010,10 @@ var ts; } } case 213: { - var result = transformVariableStatement(input); - lateStatementReplacementMap.set("" + ts.getNodeId(input), result); - return cleanup(input); + return cleanup(transformVariableStatement(input, isPrivate)); } case 237: { - return cleanup(ts.updateEnumDeclaration(input, undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(ts.updateEnumDeclaration(input, undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; var constValue = resolver.getConstantValue(m); @@ -59161,26 +60022,20 @@ var ts; } } return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); - function cleanup(returnValue) { + function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; } - if (input.kind === 238) { - needsDeclare = previousNeedsDeclare; - lateMarkedStatements = ts.concatenate(oldPossibleImports, lateMarkedStatements); - } if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (returnValue && (!ts.isLateVisibilityPaintedStatement(input) || lateStatementReplacementMap.get("" + ts.getNodeId(input)))) { - if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1) && ts.isSourceFile(input.parent)) { - resultHasExternalModuleIndicator = true; - } + if (input.kind === 238) { + needsDeclare = previousNeedsDeclare; } - if (returnValue === input) { - return returnValue; + if (node === input) { + return node; } - return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } function transformVariableStatement(input, privateDeclaration) { @@ -59257,7 +60112,7 @@ var ts; return maskModifierFlags(node, mask, additions); } function ensureAccessor(node) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + var accessors = resolver.getAllAccessorDeclarations(node); if (node.kind !== accessors.firstAccessor.kind) { return; } @@ -59269,7 +60124,7 @@ var ts; var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -59283,7 +60138,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -59431,7 +60286,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(300); + var enabledSyntaxKindFeatures = new Array(304); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -59808,7 +60663,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 295 + if (node.kind !== 299 && (emitFlags & 16) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -59825,7 +60680,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 295 + if (node.kind !== 299 && (emitFlags & 32) === 0 && end >= 0) { emitPos(end); @@ -59967,7 +60822,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295; + var isEmittedNode = node.kind !== 299; var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; if (!skipLeadingComments) { @@ -60262,13 +61117,14 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var bundle = ts.createBundle(sourceFiles); + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; @@ -60293,7 +61149,8 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); @@ -60301,14 +61158,23 @@ var ts; var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json"; + } if (options.jsx === 1) { if (ts.isSourceFileJavaScript(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { @@ -60321,7 +61187,8 @@ var ts; } return ".js"; } - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { + ts.getOutputExtension = getOutputExtension; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; @@ -60335,6 +61202,7 @@ var ts; mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, }); + var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; ts.performance.mark("beforePrint"); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); @@ -60346,8 +61214,8 @@ var ts; sourceMaps: sourceMapDataList }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -60359,10 +61227,12 @@ var ts; if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } } - function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { - var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { emitSkipped = true; return; @@ -60370,7 +61240,7 @@ var ts; if (emitOnlyDtsFiles) { return; } - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, false); + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, false); var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { hasGlobalName: resolver.hasGlobalName, onEmitNode: transform.emitNodeWithNotification, @@ -60380,7 +61250,8 @@ var ts; onEmitSourceMapOfPosition: sourceMap.emitPos, onSetSourceFile: setSourceFile, }); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { @@ -60389,8 +61260,8 @@ var ts; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); - var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; - var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], false); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), false); if (ts.length(declarationTransform.diagnostics)) { for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { var diagnostic = _b[_a]; @@ -60409,17 +61280,18 @@ var ts; var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], undefined, declarationPrinter, declarationSourceMap); } declarationTransform.dispose(); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 274 ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 273 ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { - printer.writeBundle(bundle, writer); + printer.writeBundle(bundle, writer, bundleInfo); } else { printer.writeFile(sourceFile, writer); @@ -60433,8 +61305,13 @@ var ts; ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), false, sourceFiles); } ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), false); + } mapRecorder.reset(); writer.clear(); + bundleInfo = createDefaultBundleInfo(); } function setSourceFile(node) { sourceMap.setSourceFile(node); @@ -60444,6 +61321,13 @@ var ts; } } ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } @@ -60499,6 +61383,7 @@ var ts; switch (node.kind) { case 273: return printFile(node); case 274: return printBundle(node); + case 275: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -60515,6 +61400,10 @@ var ts; writeFile(sourceFile, beginPrint()); return endPrint(); } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; setWriter(output); @@ -60532,7 +61421,7 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output) { + function writeBundle(bundle, output, bundleInfo) { isOwnFileEmit = false; var previousWriter = writer; setWriter(output); @@ -60540,13 +61429,28 @@ var ts; emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); - for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { - var sourceFile = _b[_a]; + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + print(4, prepend, undefined); + writeLine(); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; print(0, sourceFile, sourceFile); } reset(); writer = previousWriter; } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output); + print(4, unparsed, undefined); + reset(); + writer = previousWriter; + } function writeFile(sourceFile, output) { isOwnFileEmit = true; var previousWriter = writer; @@ -60569,7 +61473,8 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmitWithNotification(hint, node); + var pipelinePhase = getPipelinePhase(0, hint); + pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -60592,386 +61497,396 @@ var ts; comments.reset(); setWriter(undefined); } - function emitIfPresent(node) { - if (node) { - emit(node); - } - } function emit(node) { - pipelineEmitWithNotification(4, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0, 4); + pipelinePhase(4, node); } function emitIdentifierName(node) { - pipelineEmitWithNotification(2, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0, 2); + pipelinePhase(2, node); } function emitExpression(node) { - pipelineEmitWithNotification(1, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0, 1); + pipelinePhase(1, node); + } + function getPipelinePhase(phase, hint) { + switch (phase) { + case 0: + if (onEmitNode) { + return pipelineEmitWithNotification; + } + case 1: + if (emitNodeWithComments && hint !== 0) { + return pipelineEmitWithComments; + } + return pipelineEmitWithoutComments; + case 2: + if (onEmitSourceMapOfNode && hint !== 0 && hint !== 2) { + return pipelineEmitWithSourceMap; + } + case 3: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + } + } + function getNextPipelinePhase(currentPhase, hint) { + return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - if (onEmitNode) { - onEmitNode(hint, node, pipelineEmitWithComments); - } - else { - pipelineEmitWithComments(hint, node); - } + ts.Debug.assertDefined(onEmitNode); + onEmitNode(hint, node, getNextPipelinePhase(0, hint)); } function pipelineEmitWithComments(hint, node) { - node = trySubstituteNode(hint, node); - if (emitNodeWithComments && hint !== 0) { - emitNodeWithComments(hint, node, pipelineEmitWithSourceMap); - } - else { - pipelineEmitWithSourceMap(hint, node); - } + ts.Debug.assertDefined(emitNodeWithComments); + ts.Debug.assert(hint !== 0); + emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1, hint)); + } + function pipelineEmitWithoutComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(1, hint); + pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - if (onEmitSourceMapOfNode && hint !== 0 && hint !== 2) { - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); - } - else { - pipelineEmitWithHint(hint, node); - } + ts.Debug.assertDefined(onEmitSourceMapOfNode); + ts.Debug.assert(hint !== 0 && hint !== 2); + onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { - switch (hint) { - case 0: return pipelineEmitSourceFile(node); - case 2: return pipelineEmitIdentifierName(node); - case 1: return pipelineEmitExpression(node); - case 3: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 4: return pipelineEmitUnspecified(node); + if (hint === 0) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 4) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + case 14: + case 15: + case 16: + return emitLiteral(node); + case 275: + return emitUnparsedSource(node); + case 71: + return emitIdentifier(node); + case 145: + return emitQualifiedName(node); + case 146: + return emitComputedPropertyName(node); + case 147: + return emitTypeParameter(node); + case 148: + return emitParameter(node); + case 149: + return emitDecorator(node); + case 150: + return emitPropertySignature(node); + case 151: + return emitPropertyDeclaration(node); + case 152: + return emitMethodSignature(node); + case 153: + return emitMethodDeclaration(node); + case 154: + return emitConstructor(node); + case 155: + case 156: + return emitAccessorDeclaration(node); + case 157: + return emitCallSignature(node); + case 158: + return emitConstructSignature(node); + case 159: + return emitIndexSignature(node); + case 160: + return emitTypePredicate(node); + case 161: + return emitTypeReference(node); + case 162: + return emitFunctionType(node); + case 283: + return emitJSDocFunctionType(node); + case 163: + return emitConstructorType(node); + case 164: + return emitTypeQuery(node); + case 165: + return emitTypeLiteral(node); + case 166: + return emitArrayType(node); + case 167: + return emitTupleType(node); + case 168: + return emitUnionType(node); + case 169: + return emitIntersectionType(node); + case 170: + return emitConditionalType(node); + case 171: + return emitInferType(node); + case 172: + return emitParenthesizedType(node); + case 206: + return emitExpressionWithTypeArguments(node); + case 173: + return emitThisType(); + case 174: + return emitTypeOperator(node); + case 175: + return emitIndexedAccessType(node); + case 176: + return emitMappedType(node); + case 177: + return emitLiteralType(node); + case 178: + return emitImportTypeNode(node); + case 278: + write("*"); + return; + case 279: + write("?"); + return; + case 280: + return emitJSDocNullableType(node); + case 281: + return emitJSDocNonNullableType(node); + case 282: + return emitJSDocOptionalType(node); + case 284: + return emitJSDocVariadicType(node); + case 179: + return emitObjectBindingPattern(node); + case 180: + return emitArrayBindingPattern(node); + case 181: + return emitBindingElement(node); + case 210: + return emitTemplateSpan(node); + case 211: + return emitSemicolonClassElement(); + case 212: + return emitBlock(node); + case 213: + return emitVariableStatement(node); + case 214: + return emitEmptyStatement(); + case 215: + return emitExpressionStatement(node); + case 216: + return emitIfStatement(node); + case 217: + return emitDoStatement(node); + case 218: + return emitWhileStatement(node); + case 219: + return emitForStatement(node); + case 220: + return emitForInStatement(node); + case 221: + return emitForOfStatement(node); + case 222: + return emitContinueStatement(node); + case 223: + return emitBreakStatement(node); + case 224: + return emitReturnStatement(node); + case 225: + return emitWithStatement(node); + case 226: + return emitSwitchStatement(node); + case 227: + return emitLabeledStatement(node); + case 228: + return emitThrowStatement(node); + case 229: + return emitTryStatement(node); + case 230: + return emitDebuggerStatement(node); + case 231: + return emitVariableDeclaration(node); + case 232: + return emitVariableDeclarationList(node); + case 233: + return emitFunctionDeclaration(node); + case 234: + return emitClassDeclaration(node); + case 235: + return emitInterfaceDeclaration(node); + case 236: + return emitTypeAliasDeclaration(node); + case 237: + return emitEnumDeclaration(node); + case 238: + return emitModuleDeclaration(node); + case 239: + return emitModuleBlock(node); + case 240: + return emitCaseBlock(node); + case 241: + return emitNamespaceExportDeclaration(node); + case 242: + return emitImportEqualsDeclaration(node); + case 243: + return emitImportDeclaration(node); + case 244: + return emitImportClause(node); + case 245: + return emitNamespaceImport(node); + case 246: + return emitNamedImports(node); + case 247: + return emitImportSpecifier(node); + case 248: + return emitExportAssignment(node); + case 249: + return emitExportDeclaration(node); + case 250: + return emitNamedExports(node); + case 251: + return emitExportSpecifier(node); + case 252: + return; + case 253: + return emitExternalModuleReference(node); + case 10: + return emitJsxText(node); + case 256: + case 259: + return emitJsxOpeningElementOrFragment(node); + case 257: + case 260: + return emitJsxClosingElementOrFragment(node); + case 261: + return emitJsxAttribute(node); + case 262: + return emitJsxAttributes(node); + case 263: + return emitJsxSpreadAttribute(node); + case 264: + return emitJsxExpression(node); + case 265: + return emitCaseClause(node); + case 266: + return emitDefaultClause(node); + case 267: + return emitHeritageClause(node); + case 268: + return emitCatchClause(node); + case 269: + return emitPropertyAssignment(node); + case 270: + return emitShorthandPropertyAssignment(node); + case 271: + return emitSpreadAssignment(node); + case 272: + return emitEnumMember(node); + } + if (ts.isExpression(node)) { + hint = 1; + node = trySubstituteNode(1, node); + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1) { + switch (node.kind) { + case 8: + return emitNumericLiteral(node); + case 9: + case 12: + case 13: + return emitLiteral(node); + case 71: + return emitIdentifier(node); + case 86: + case 95: + case 97: + case 101: + case 99: + case 91: + writeTokenNode(node, writeKeyword); + return; + case 182: + return emitArrayLiteralExpression(node); + case 183: + return emitObjectLiteralExpression(node); + case 184: + return emitPropertyAccessExpression(node); + case 185: + return emitElementAccessExpression(node); + case 186: + return emitCallExpression(node); + case 187: + return emitNewExpression(node); + case 188: + return emitTaggedTemplateExpression(node); + case 189: + return emitTypeAssertionExpression(node); + case 190: + return emitParenthesizedExpression(node); + case 191: + return emitFunctionExpression(node); + case 192: + return emitArrowFunction(node); + case 193: + return emitDeleteExpression(node); + case 194: + return emitTypeOfExpression(node); + case 195: + return emitVoidExpression(node); + case 196: + return emitAwaitExpression(node); + case 197: + return emitPrefixUnaryExpression(node); + case 198: + return emitPostfixUnaryExpression(node); + case 199: + return emitBinaryExpression(node); + case 200: + return emitConditionalExpression(node); + case 201: + return emitTemplateExpression(node); + case 202: + return emitYieldExpression(node); + case 203: + return emitSpreadExpression(node); + case 204: + return emitClassExpression(node); + case 205: + return; + case 207: + return emitAsExpression(node); + case 208: + return emitNonNullExpression(node); + case 209: + return emitMetaProperty(node); + case 254: + return emitJsxElement(node); + case 255: + return emitJsxSelfClosingElement(node); + case 258: + return emitJsxFragment(node); + case 300: + return emitPartiallyEmittedExpression(node); + case 301: + return emitCommaList(node); + } } - } - function pipelineEmitSourceFile(node) { - ts.Debug.assertNode(node, ts.isSourceFile); - emitSourceFile(node); - } - function pipelineEmitIdentifierName(node) { - ts.Debug.assertNode(node, ts.isIdentifier); - emitIdentifier(node); } function emitMappedTypeParameter(node) { emit(node.name); writeSpace(); writeKeyword("in"); writeSpace(); - emitIfPresent(node.constraint); - } - function pipelineEmitUnspecified(node) { - var kind = node.kind; - if (ts.isKeyword(kind)) { - writeTokenNode(node, writeKeyword); - return; - } - switch (kind) { - case 14: - case 15: - case 16: - return emitLiteral(node); - case 71: - return emitIdentifier(node); - case 145: - return emitQualifiedName(node); - case 146: - return emitComputedPropertyName(node); - case 147: - return emitTypeParameter(node); - case 148: - return emitParameter(node); - case 149: - return emitDecorator(node); - case 150: - return emitPropertySignature(node); - case 151: - return emitPropertyDeclaration(node); - case 152: - return emitMethodSignature(node); - case 153: - return emitMethodDeclaration(node); - case 154: - return emitConstructor(node); - case 155: - case 156: - return emitAccessorDeclaration(node); - case 157: - return emitCallSignature(node); - case 158: - return emitConstructSignature(node); - case 159: - return emitIndexSignature(node); - case 160: - return emitTypePredicate(node); - case 161: - return emitTypeReference(node); - case 162: - return emitFunctionType(node); - case 281: - return emitJSDocFunctionType(node); - case 163: - return emitConstructorType(node); - case 164: - return emitTypeQuery(node); - case 165: - return emitTypeLiteral(node); - case 166: - return emitArrayType(node); - case 167: - return emitTupleType(node); - case 168: - return emitUnionType(node); - case 169: - return emitIntersectionType(node); - case 170: - return emitConditionalType(node); - case 171: - return emitInferType(node); - case 172: - return emitParenthesizedType(node); - case 206: - return emitExpressionWithTypeArguments(node); - case 173: - return emitThisType(); - case 174: - return emitTypeOperator(node); - case 175: - return emitIndexedAccessType(node); - case 176: - return emitMappedType(node); - case 177: - return emitLiteralType(node); - case 178: - return emitImportTypeNode(node); - case 276: - write("*"); - return; - case 277: - write("?"); - return; - case 278: - return emitJSDocNullableType(node); - case 279: - return emitJSDocNonNullableType(node); - case 280: - return emitJSDocOptionalType(node); - case 282: - return emitJSDocVariadicType(node); - case 179: - return emitObjectBindingPattern(node); - case 180: - return emitArrayBindingPattern(node); - case 181: - return emitBindingElement(node); - case 210: - return emitTemplateSpan(node); - case 211: - return emitSemicolonClassElement(); - case 212: - return emitBlock(node); - case 213: - return emitVariableStatement(node); - case 214: - return emitEmptyStatement(); - case 215: - return emitExpressionStatement(node); - case 216: - return emitIfStatement(node); - case 217: - return emitDoStatement(node); - case 218: - return emitWhileStatement(node); - case 219: - return emitForStatement(node); - case 220: - return emitForInStatement(node); - case 221: - return emitForOfStatement(node); - case 222: - return emitContinueStatement(node); - case 223: - return emitBreakStatement(node); - case 224: - return emitReturnStatement(node); - case 225: - return emitWithStatement(node); - case 226: - return emitSwitchStatement(node); - case 227: - return emitLabeledStatement(node); - case 228: - return emitThrowStatement(node); - case 229: - return emitTryStatement(node); - case 230: - return emitDebuggerStatement(node); - case 231: - return emitVariableDeclaration(node); - case 232: - return emitVariableDeclarationList(node); - case 233: - return emitFunctionDeclaration(node); - case 234: - return emitClassDeclaration(node); - case 235: - return emitInterfaceDeclaration(node); - case 236: - return emitTypeAliasDeclaration(node); - case 237: - return emitEnumDeclaration(node); - case 238: - return emitModuleDeclaration(node); - case 239: - return emitModuleBlock(node); - case 240: - return emitCaseBlock(node); - case 241: - return emitNamespaceExportDeclaration(node); - case 242: - return emitImportEqualsDeclaration(node); - case 243: - return emitImportDeclaration(node); - case 244: - return emitImportClause(node); - case 245: - return emitNamespaceImport(node); - case 246: - return emitNamedImports(node); - case 247: - return emitImportSpecifier(node); - case 248: - return emitExportAssignment(node); - case 249: - return emitExportDeclaration(node); - case 250: - return emitNamedExports(node); - case 251: - return emitExportSpecifier(node); - case 252: - return; - case 253: - return emitExternalModuleReference(node); - case 10: - return emitJsxText(node); - case 256: - case 259: - return emitJsxOpeningElementOrFragment(node); - case 257: - case 260: - return emitJsxClosingElementOrFragment(node); - case 261: - return emitJsxAttribute(node); - case 262: - return emitJsxAttributes(node); - case 263: - return emitJsxSpreadAttribute(node); - case 264: - return emitJsxExpression(node); - case 265: - return emitCaseClause(node); - case 266: - return emitDefaultClause(node); - case 267: - return emitHeritageClause(node); - case 268: - return emitCatchClause(node); - case 269: - return emitPropertyAssignment(node); - case 270: - return emitShorthandPropertyAssignment(node); - case 271: - return emitSpreadAssignment(node); - case 272: - return emitEnumMember(node); - } - if (ts.isExpression(node)) { - return pipelineEmitExpression(trySubstituteNode(1, node)); - } - if (ts.isToken(node)) { - writeTokenNode(node, writePunctuation); - return; - } - } - function pipelineEmitExpression(node) { - var kind = node.kind; - switch (kind) { - case 8: - return emitNumericLiteral(node); - case 9: - case 12: - case 13: - return emitLiteral(node); - case 71: - return emitIdentifier(node); - case 86: - case 95: - case 97: - case 101: - case 99: - case 91: - writeTokenNode(node, writeKeyword); - return; - case 182: - return emitArrayLiteralExpression(node); - case 183: - return emitObjectLiteralExpression(node); - case 184: - return emitPropertyAccessExpression(node); - case 185: - return emitElementAccessExpression(node); - case 186: - return emitCallExpression(node); - case 187: - return emitNewExpression(node); - case 188: - return emitTaggedTemplateExpression(node); - case 189: - return emitTypeAssertionExpression(node); - case 190: - return emitParenthesizedExpression(node); - case 191: - return emitFunctionExpression(node); - case 192: - return emitArrowFunction(node); - case 193: - return emitDeleteExpression(node); - case 194: - return emitTypeOfExpression(node); - case 195: - return emitVoidExpression(node); - case 196: - return emitAwaitExpression(node); - case 197: - return emitPrefixUnaryExpression(node); - case 198: - return emitPostfixUnaryExpression(node); - case 199: - return emitBinaryExpression(node); - case 200: - return emitConditionalExpression(node); - case 201: - return emitTemplateExpression(node); - case 202: - return emitYieldExpression(node); - case 203: - return emitSpreadExpression(node); - case 204: - return emitClassExpression(node); - case 205: - return; - case 207: - return emitAsExpression(node); - case 208: - return emitNonNullExpression(node); - case 209: - return emitMetaProperty(node); - case 254: - return emitJsxElement(node); - case 255: - return emitJsxSelfClosingElement(node); - case 258: - return emitJsxFragment(node); - case 296: - return emitPartiallyEmittedExpression(node); - case 297: - return emitCommaList(node); - } + emit(node.constraint); } function trySubstituteNode(hint, node) { return node && substituteNode && substituteNode(hint, node) || node; @@ -61030,6 +61945,9 @@ var ts; writeStringLiteral(text); } } + function emitUnparsedSource(unparsed) { + write(unparsed.text); + } function emitIdentifier(node) { var writeText = node.symbol ? writeSymbol : write; writeText(getTextOfNode(node, false), node.symbol); @@ -61071,13 +61989,11 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.dotDotDotToken); - if (node.name) { - emitNodeWithWriter(node.name, writeParameter); - } - emitIfPresent(node.questionToken); - if (node.parent && node.parent.kind === 281 && !node.name) { - emitIfPresent(node.type); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 283 && !node.name) { + emit(node.type); } else { emitTypeAnnotation(node.type); @@ -61092,7 +62008,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeAnnotation(node.type); writeSemicolon(); } @@ -61100,28 +62016,30 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); - emitIfPresent(node.exclamationToken); + emit(node.questionToken); + emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -61138,14 +62056,17 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitCallSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitConstructSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("new"); @@ -61154,6 +62075,7 @@ var ts; emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); @@ -61177,18 +62099,20 @@ var ts; emitTypeArguments(node, node.typeArguments); } function emitFunctionType(node) { + pushNameGenerationScope(node); emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitJSDocFunctionType(node) { write("function"); emitParameters(node, node.parameters); write(":"); - emitIfPresent(node.type); + emit(node.type); } function emitJSDocNullableType(node) { write("?"); @@ -61203,6 +62127,7 @@ var ts; write("="); } function emitConstructorType(node) { + pushNameGenerationScope(node); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -61210,7 +62135,8 @@ var ts; writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitTypeQuery(node) { writeKeyword("typeof"); @@ -61300,7 +62226,8 @@ var ts; writeSpace(); } writePunctuation("["); - pipelineEmitWithNotification(3, node.typeParameter); + var pipelinePhase = getPipelinePhase(0, 3); + pipelinePhase(3, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); @@ -61310,7 +62237,7 @@ var ts; } writePunctuation(":"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); writeSemicolon(); if (emitFlags & 1) { writeSpace(); @@ -61350,7 +62277,7 @@ var ts; writePunctuation("]"); } function emitBindingElement(node) { - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); if (node.propertyName) { emit(node.propertyName); writePunctuation(":"); @@ -61365,6 +62292,7 @@ var ts; emitExpressionList(node, elements, 4466 | preferNewLine); } function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); @@ -61449,6 +62377,7 @@ var ts; emitTokenWithComment(20, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { @@ -61536,7 +62465,7 @@ var ts; } function emitYieldExpression(node) { emitTokenWithComment(116, node.pos, writeKeyword, node); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { @@ -61544,6 +62473,7 @@ var ts; emitExpression(node.expression); } function emitClassExpression(node) { + generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { @@ -61591,7 +62521,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - writeSemicolon(); + if (!ts.isJsonSourceFile(currentSourceFile)) { + writeSemicolon(); + } } function emitIfStatement(node) { var openParenPos = emitTokenWithComment(90, node.pos, writeKeyword, node); @@ -61784,7 +62716,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -61801,6 +62733,8 @@ var ts; increaseIndent(); } pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); emitSignatureHead(node); if (onEmitNode) { onEmitNode(4, body, emitBlockCallback); @@ -61889,6 +62823,7 @@ var ts; emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("class"); @@ -61966,6 +62901,7 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitBlockStatements(node, isEmptyBlock(node)); popNameGenerationScope(node); } @@ -62007,12 +62943,12 @@ var ts; writeSemicolon(); } function emitImportClause(node) { - emitIfPresent(node.name); + emit(node.name); if (node.name && node.namedBindings) { emitTokenWithComment(26, node.name.end, writePunctuation, node); writeSpace(); } - emitIfPresent(node.namedBindings); + emit(node.namedBindings); } function emitNamespaceImport(node) { var asPos = emitTokenWithComment(39, node.pos, writePunctuation, node); @@ -62148,7 +63084,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { writePunctuation("{"); - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); emitExpression(node.expression); writePunctuation("}"); } @@ -62281,8 +63217,8 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { - var directive = types_18[_d]; + for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { + var directive = types_17[_d]; write("/// "); writeLine(); } @@ -62290,6 +63226,7 @@ var ts; function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); @@ -62356,6 +63293,8 @@ var ts; } } function emitNodeWithWriter(node, writer) { + if (!node) + return; var savedWrite = write; write = writer; emit(node); @@ -62816,7 +63755,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return generateName(node); } - else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } else if (node.kind === 9 && node.textSourceNode) { @@ -62862,28 +63801,125 @@ var ts; } reservedNames.set(name, true); } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 212: + ts.forEach(node.statements, generateNames); + break; + case 227: + case 225: + case 217: + case 218: + generateNames(node.statement); + break; + case 216: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 219: + case 221: + case 220: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 226: + generateNames(node.caseBlock); + break; + case 240: + ts.forEach(node.clauses, generateNames); + break; + case 265: + case 266: + ts.forEach(node.statements, generateNames); + break; + case 229: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 268: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 213: + generateNames(node.declarationList); + break; + case 232: + ts.forEach(node.declarations, generateNames); + break; + case 231: + case 148: + case 181: + case 234: + generateNameIfNeeded(node.name); + break; + case 233: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 179: + case 180: + ts.forEach(node.elements, generateNames); + break; + case 243: + generateNames(node.importClause); + break; + case 244: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 245: + generateNameIfNeeded(node.name); + break; + case 246: + ts.forEach(node.elements, generateNames); + break; + case 247: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 269: + case 270: + case 151: + case 153: + case 155: + case 156: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } function generateName(name) { if ((name.autoGenerateFlags & 7) === 4) { - if (name.autoGenerateFlags & 8) { - var savedTempFlags = tempFlags; - popNameGenerationScope(undefined); - var result = generateNameCached(getNodeForGeneratedName(name)); - pushNameGenerationScope(undefined); - tempFlags = savedTempFlags; - return result; - } - else { - return generateNameCached(getNodeForGeneratedName(name)); - } + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); } else { var autoGenerateId = name.autoGenerateId; return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } - function generateNameCached(node) { + function generateNameCached(node, flags) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); } function isUniqueName(name) { return isFileLevelUniqueName(name) @@ -62891,7 +63927,7 @@ var ts; && !(reservedNames && reservedNames.has(name)); } function isFileLevelUniqueName(name) { - return ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName); + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; } function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { @@ -62931,11 +63967,16 @@ var ts; } } } - function makeUniqueName(baseName, checkFn, optimistic) { + function makeUniqueName(baseName, checkFn, optimistic, scoped) { if (checkFn === void 0) { checkFn = isUniqueName; } if (optimistic) { if (checkFn(baseName)) { - generatedNames.set(baseName, true); + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } return baseName; } } @@ -62946,7 +63987,12 @@ var ts; while (true) { var generatedName = baseName + i; if (checkFn(generatedName)) { - generatedNames.set(generatedName, true); + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } return generatedName; } i++; @@ -62977,10 +64023,10 @@ var ts; } return makeTempVariableName(0); } - function generateNameForNode(node) { + function generateNameForNode(node, flags) { switch (node.kind) { case 71: - return makeUniqueName(getTextOfNode(node)); + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16), !!(flags & 8)); case 238: case 237: return generateNameForModuleOrEnum(node); @@ -63004,11 +64050,11 @@ var ts; function makeName(name) { switch (name.autoGenerateFlags & 7) { case 1: - return makeTempVariableName(0, !!(name.autoGenerateFlags & 16)); + return makeTempVariableName(0, !!(name.autoGenerateFlags & 8)); case 2: - return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 16)); + return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 8)); case 3: - return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 64) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 32)); + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16), !!(name.autoGenerateFlags & 8)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -63019,7 +64065,7 @@ var ts; while (original) { node = original; if (ts.isIdentifier(node) - && node.autoGenerateFlags === 4 + && !!(node.autoGenerateFlags & 4) && node.autoGenerateId !== autoGenerateId) { break; } @@ -63075,7 +64121,7 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); } function getCachedFileSystemEntriesForBaseDir(path) { return getCachedFileSystemEntries(ts.getDirectoryPath(path)); @@ -63088,10 +64134,11 @@ var ts; files: ts.map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], directories: host.getDirectories(rootDir) || [] }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); return resultFromHost; } function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); var cachedResult = getCachedFileSystemEntries(rootDirPath); if (cachedResult) { return cachedResult; @@ -63100,7 +64147,7 @@ var ts; return createCachedFileSystemEntries(rootDir, rootDirPath); } catch (_e) { - ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); return undefined; } } @@ -63136,7 +64183,7 @@ var ts; } function directoryExists(dirPath) { var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); } function createDirectory(dirPath) { var path = toPath(dirPath); @@ -63376,7 +64423,7 @@ var ts; if (!commonPathComponents) { return currentDirectory; } - return ts.getNormalizedPathFromPathComponents(commonPathComponents); + return ts.getPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { @@ -63480,7 +64527,8 @@ var ts; directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, - realpath: realpath + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); } }; } ts.createCompilerHost = createCompilerHost; @@ -63692,7 +64740,19 @@ var ts; oldOptions.baseUrl !== newOptions.baseUrl || !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); } - function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -63710,6 +64770,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -63718,6 +64779,7 @@ var ts; var supportedExtensions = ts.getSupportedExtensions(options); var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; + var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; @@ -63750,6 +64812,22 @@ var ts; var filesByName = ts.createMap(); var missingFilePaths; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + var resolvedProjectReferences = projectReferences ? [] : undefined; + var projectReferenceRedirects = ts.createMap(); + if (projectReferences) { + for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { + var ref = projectReferences_1[_i]; + var parsedRef = parseProjectReferenceConfigFile(ref); + resolvedProjectReferences.push(parsedRef); + if (parsedRef) { + if (parsedRef.commandLine.options.outFile) { + var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + processSourceFile(dtsOutfile, false, undefined); + } + addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + } + } + } var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { @@ -63779,8 +64857,8 @@ var ts; ts.Debug.assert(!!missingFilePaths); if (oldProgram && host.onReleaseOldSourceFile) { var oldSourceFiles = oldProgram.getSourceFiles(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); } @@ -63820,6 +64898,7 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -63837,6 +64916,10 @@ var ts; if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } + else if (options.composite) { + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } else { commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } @@ -63863,13 +64946,13 @@ var ts; } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } var unknownModuleNames; var result; @@ -63965,6 +65048,31 @@ var ts; if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { return oldProgram.structureIsReused = 0; } + var oldRefs = oldProgram.getProjectReferences(); + if (projectReferences) { + if (!oldRefs) { + return oldProgram.structureIsReused = 0; + } + for (var i = 0; i < projectReferences.length; i++) { + var oldRef = oldRefs[i]; + if (oldRef) { + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); + if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { + return oldProgram.structureIsReused = 0; + } + } + else { + if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + return oldProgram.structureIsReused = 0; + } + } + } + } + else { + if (oldRefs) { + return oldProgram.structureIsReused = 0; + } + } var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; @@ -64103,6 +65211,7 @@ var ts; } function getEmitHost(writeFileCallback) { return { + getPrependNodes: getPrependNodes, getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, @@ -64116,6 +65225,31 @@ var ts; isEmitBlocked: isEmitBlocked, }; } + function getProjectReferences() { + if (!resolvedProjectReferences) + return; + return resolvedProjectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + if (!resolvedRefOpts.options.outFile) + continue; + var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); + var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var node = ts.createInputFiles(js, dts); + nodes.push(node); + } + } + return nodes; + } function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } @@ -64173,7 +65307,7 @@ var ts; var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -64243,7 +65377,7 @@ var ts; ts.Debug.assert(!!sourceFile.bindDiagnostics); var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 || sourceFile.scriptKind === 4 || - sourceFile.scriptKind === 5 || isCheckJs; + sourceFile.scriptKind === 5 || isCheckJs || sourceFile.scriptKind === 7; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -64578,7 +65712,13 @@ var ts; var sourceFile = getSourceFile(fileName); if (fail) { if (!sourceFile) { - fail(ts.Diagnostics.File_0_not_found, fileName); + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); @@ -64658,6 +65798,15 @@ var ts; } return file_1; } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + redirectedPath = toPath(redirect); + } + } var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); @@ -64683,6 +65832,9 @@ var ts; } } filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; @@ -64711,6 +65863,20 @@ var ts; } return file; } + function getProjectReferenceRedirect(fileName) { + var path = toPath(fileName); + var normalized = ts.getNormalizedAbsolutePath(fileName, path); + var result; + projectReferenceRedirects.forEach(function (v, k) { + if (result !== undefined) { + return undefined; + } + if (normalized.indexOf(k) === 0) { + result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); + } + }); + return result; + } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); @@ -64719,6 +65885,9 @@ var ts; } function processTypeReferenceDirectives(file) { var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; @@ -64789,7 +65958,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -64847,6 +66016,25 @@ var ts; } return allFilesBelongToPath; } + function parseProjectReferenceConfigFile(ref) { + var refPath = resolveProjectReferencePath(host, ref); + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100); + if (sourceFile === undefined) { + return undefined; + } + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, undefined, refPath); + return { commandLine: commandLine, sourceFile: sourceFile }; + } + function addProjectReferenceRedirects(referencedProject, target) { + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); + target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); + } + function getDeclarationOutputDirectory(proj) { + return proj.options.declarationDir || + proj.options.outDir || + ts.getDirectoryPath(proj.options.configFilePath); + } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !options.strictNullChecks) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); @@ -64876,6 +66064,47 @@ var ts; if (options.paths && options.baseUrl === undefined) { createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + if (projectReferences) { + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; + if (resolvedRefOpts === undefined) { + createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); + continue; + } + if (!resolvedRefOpts.composite) { + createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + if (ref.prepend) { + if (resolvedRefOpts.outFile) { + if (!host.fileExists(resolvedRefOpts.outFile)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + } + } + else { + createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + } + } + if (options.composite && rootNames.length < files.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); + var _loop_10 = function (file) { + if (normalizedRootNames.every(function (r) { return r !== file; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } + }; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var file = sourceFiles_4[_i]; + _loop_10(file); + } + } if (options.paths) { for (var key in options.paths) { if (!ts.hasProperty(options.paths, key)) { @@ -64964,6 +66193,11 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + } if (options.outDir || options.sourceRoot || options.mapRoot) { @@ -65066,12 +66300,15 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); } } - function getOptionPathsSyntax() { + function getOptionsSyntaxByName(name) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); if (compilerOptionsObjectLiteralSyntax) { - return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); } - return ts.emptyArray; + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; } function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(true, option1, option2, message, option1, option2, option3); @@ -65079,6 +66316,15 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(false, option1, undefined, message, arg0); } + function createDiagnosticForReference(index, message, arg0, arg1) { + var referencesSyntax = getProjectReferencesSyntax(); + if (referencesSyntax) { + if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { + return; + } + } + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || @@ -65087,11 +66333,28 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } + function getProjectReferencesSyntax() { + if (_referencesArrayLiteralSyntax === undefined) { + _referencesArrayLiteralSyntax = null; + if (options.configFile) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isArrayLiteralExpression(prop.initializer)) { + _referencesArrayLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _referencesArrayLiteralSyntax; + } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; - if (options.configFile && options.configFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { var prop = _a[_i]; if (ts.isObjectLiteralExpression(prop.initializer)) { _compilerOptionsObjectLiteralSyntax = prop.initializer; @@ -65110,6 +66373,12 @@ var ts; } return !!props.length; } + function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { + if (arrayLiteral.elements.length <= index) { + return false; + } + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -65141,11 +66410,29 @@ var ts; } } ts.createProgram = createProgram; + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + function resolveProjectReferencePath(host, ref) { + if (!host.fileExists(ref.path)) { + return ts.combinePaths(ref.path, "tsconfig.json"); + } + return ref.path; + } function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { case ".ts": case ".d.ts": + case ".json": return undefined; case ".tsx": return needJsx(); @@ -65308,6 +66595,7 @@ var ts; return !prevSignature || latestSignature !== prevSignature; } function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; var compilerOptions = programOfThisState.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { return getAllFileNames(state, programOfThisState); @@ -65324,7 +66612,7 @@ var ts; var references = state.referencedMap.get(path); if (references) { var iterator = references.keys(); - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { queue.push(value); } } @@ -65334,7 +66622,6 @@ var ts; var file = programOfThisState.getSourceFileByPath(path); return file ? file.fileName : path; })); - var _b; } BuilderState.getAllDependencies = getAllDependencies; function getAllFileNames(state, programOfThisState) { @@ -65656,8 +66943,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_1 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -65721,6 +67008,7 @@ var ts; startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, @@ -65879,6 +67167,10 @@ var ts; function resolveModuleNames(moduleNames, containingFile, reusedNames) { return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } @@ -65917,17 +67209,19 @@ var ts; if (isNodeModulesDirectory(dirPath)) { return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } + var subDirectory; if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { var parentPath = ts.getDirectoryPath(dirPath); if (parentPath === dirPath) { break; } + subDirectory = dirPath.slice(parentPath.length + ts.directorySeparator.length); dirPath = parentPath; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath, subDirectory: subDirectory }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -65946,7 +67240,7 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; @@ -65956,7 +67250,7 @@ var ts; setAtRoot = true; } else { - setDirectoryWatcher(dir, dirPath); + setDirectoryWatcher(dir, dirPath, subDirectory); } } } @@ -65964,13 +67258,19 @@ var ts; setDirectoryWatcher(rootDir, rootPath); } } - function setDirectoryWatcher(dir, dirPath) { + function setDirectoryWatcher(dir, dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { dirWatcher.refCount++; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }; + directoryWatchesOfFailedLookups.set(dirPath, dirWatcher); + } + if (subDirectory) { + var subDirectoryMap = dirWatcher.subDirectoryMap || (dirWatcher.subDirectoryMap = ts.createMap()); + var existing = subDirectoryMap.get(subDirectory) || 0; + subDirectoryMap.set(subDirectory, existing + 1); } } function stopWatchFailedLookupLocationOfResolution(resolution) { @@ -65986,7 +67286,7 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { @@ -66002,7 +67302,7 @@ var ts; removeAtRoot = true; } else { - removeDirectoryWatcher(dirPath); + removeDirectoryWatcher(dirPath, subDirectory); } } } @@ -66010,10 +67310,28 @@ var ts; removeDirectoryWatcher(rootPath); } } - function removeDirectoryWatcher(dirPath) { + function removeDirectoryWatcher(dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (subDirectory) { + var existing = dirWatcher.subDirectoryMap.get(subDirectory); + if (existing === 1) { + dirWatcher.subDirectoryMap.delete(subDirectory); + } + else { + dirWatcher.subDirectoryMap.set(subDirectory, existing - 1); + } + } dirWatcher.refCount--; } + function inWatchedSubdirectory(dirPath, fileOrDirectoryPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (!dirWatcher || !dirWatcher.subDirectoryMap) + return false; + return ts.forEachKey(dirWatcher.subDirectoryMap, function (subDirectory) { + var fullSubDirectory = dirPath + "/" + subDirectory; + return fullSubDirectory === fileOrDirectoryPath || isInDirectoryPath(fullSubDirectory, fileOrDirectoryPath); + }); + } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); @@ -66021,7 +67339,7 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } if (!allFilesHaveInvalidatedResolution && - dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + (dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath || inWatchedSubdirectory(dirPath, fileOrDirectoryPath))) { if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { resolutionHost.onInvalidatedResolution(); } @@ -66233,31 +67551,11 @@ var ts; function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; - var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - var result = ts.parseJsonText(configFileName, configFileText); - var cwd = host.getCurrentDirectory(); - return ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); - } - ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -66326,12 +67624,12 @@ var ts; watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, setTimeout: system.setTimeout ? (function (callback, ms) { + var _a; var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - var _a; }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, trace: function (s) { return system.write(s); }, @@ -67034,6 +68332,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, { name: "removeComments", type: "boolean", @@ -67284,6 +68589,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, { name: "listFiles", type: "boolean", @@ -67565,11 +68876,13 @@ var ts; function parseCommandLine(commandLine, readFile) { var options = {}; var fileNames = []; + var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, + projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -67677,6 +68990,26 @@ var ts; } return optionNameMap.get(optionName); } + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; function readConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; @@ -67711,69 +69044,84 @@ var ts; var _tsconfigRootOptions; function getTsconfigRootOptionsMap() { if (_tsconfigRootOptions === undefined) { - _tsconfigRootOptions = commandLineOptionsToMap([ - { - name: "compilerOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 - }, - { - name: "typingOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "typeAcquisition", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "extends", - type: "string" - }, - { - name: "files", - type: "list", - element: { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { name: "files", - type: "string" - } - }, - { - name: "include", - type: "list", - element: { + type: "list", + element: { + name: "files", + type: "string" + } + }, + { name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { + type: "list", + element: { + name: "include", + type: "string" + } + }, + { name: "exclude", - type: "string" - } - }, - ts.compileOnSaveCommandLineOption - ]); + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; } return _tsconfigRootOptions; } function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, undefined, undefined); + return convertToObjectWorker(sourceFile, errors, true, undefined, undefined); } ts.convertToObject = convertToObject; - function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.jsonObject) { - return {}; + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined); function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { - var result = {}; + var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; if (element.kind !== 269) { @@ -67793,16 +69141,18 @@ var ts; } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { - result[keyText] = value; + if (returnValue) { + result[keyText] = value; + } if (jsonConversionNotifier && - (parentOption || knownOptions === knownRootOptions)) { + (parentOption || isRootOptionMap(knownOptions))) { var isValidOptionValue = isCompilerOptionsValue(option, value); if (parentOption) { if (isValidOptionValue) { jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); } } - else if (knownOptions === knownRootOptions) { + else if (isRootOptionMap(knownOptions)) { if (isValidOptionValue) { jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); } @@ -67816,7 +69166,7 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -67882,6 +69232,7 @@ var ts; return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } + ts.convertToObjectWorker = convertToObjectWorker; function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : @@ -67923,7 +69274,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_9 = function (name) { + var _loop_11 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; @@ -67947,7 +69298,7 @@ var ts; } }; for (var name in options) { - _loop_9(name); + _loop_11(name); } return result; } @@ -68064,12 +69415,13 @@ var ts; var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); - options.configFilePath = configFileName; + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; return { options: options, fileNames: fileNames, + projectReferences: projectReferences, typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), raw: raw, errors: errors, @@ -68108,19 +69460,43 @@ var ts; createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } - else { - var outDir = raw.compilerOptions && raw.compilerOptions.outDir; - if (outDir) { - excludeSpecs = [outDir]; + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); } } if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + var references = []; + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + references.push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + result.projectReferences = references; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } return result; } function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { @@ -68228,7 +69604,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertToObjectWorker(sourceFile, errors, true, getTsconfigRootOptionsMap(), optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -68262,6 +69638,7 @@ var ts; return extendedConfigPath; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -68289,7 +69666,6 @@ var ts; mapPropertiesInRawIfNotUndefined("files"); } return extendedConfig; - var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { @@ -68314,7 +69690,7 @@ var ts; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function getDefaultCompilerOptions(configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {}; return options; @@ -68322,10 +69698,13 @@ var ts; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -68419,7 +69798,7 @@ var ts; validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { @@ -68452,8 +69831,12 @@ var ts; } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { + return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); + }); return { fileNames: literalFiles.concat(wildcardFiles), + projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -68468,20 +69851,10 @@ var ts; return diag === undefined; }); function createDiagnostic(message, spec) { - if (jsonSourceFile && jsonSourceFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { - var property = _a[_i]; - if (ts.isArrayLiteralExpression(property.initializer)) { - for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (ts.isStringLiteral(element) && element.text === spec) { - return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); - } - } - } - } - } - return ts.createCompilerDiagnostic(message, spec); + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); } } function specToDiagnostic(spec, allowTrailingRecursion) { @@ -68669,6 +70042,13 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + OutliningSpanKind["Comment"] = "comment"; + OutliningSpanKind["Region"] = "region"; + OutliningSpanKind["Code"] = "code"; + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); var OutputFileType; (function (OutputFileType) { OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; @@ -68732,6 +70112,7 @@ var ts; ScriptElementKind["directory"] = "directory"; ScriptElementKind["externalModuleName"] = "external module name"; ScriptElementKind["jsxAttribute"] = "JSX attribute"; + ScriptElementKind["string"] = "string"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -68835,7 +70216,7 @@ var ts; case 236: case 165: return 2; - case 292: + case 296: return node.name === undefined ? 1 | 2 : 2; case 272: case 234: @@ -68887,6 +70268,9 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); return 2; } + else if (ts.isLiteralTypeNode(node.parent)) { + return 2 | 1; + } else { return 1; } @@ -68946,6 +70330,8 @@ var ts; switch (node.parent.kind) { case 161: return true; + case 178: + return !node.parent.isTypeOf; case 206: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } @@ -69033,7 +70419,7 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 292) { + if (ts.isJSDocTypeAlias(node)) { node = node.parent.parent; } while (true) { @@ -69068,7 +70454,10 @@ var ts; case 204: return "class"; case 235: return "interface"; - case 236: return "type"; + case 236: + case 291: + case 296: + return "type"; case 237: return "enum"; case 231: return getKindOfVariableDeclaration(node); @@ -69099,8 +70488,6 @@ var ts; case 251: case 245: return "alias"; - case 292: - return "type"; case 199: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; @@ -69158,6 +70545,10 @@ var ts; return startEndContainsRange(r1.pos, r1.end, r2); } ts.rangeContainsRange = rangeContainsRange; + function rangeContainsPosition(r, pos) { + return r.pos <= pos && pos <= r.end; + } + ts.rangeContainsPosition = rangeContainsPosition; function startEndContainsRange(start, end, range) { return start <= range.pos && end >= range.end; } @@ -69380,7 +70771,7 @@ var ts; return findPrecedingToken(position, file); } ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { + function findNextToken(previousToken, parent, sourceFile) { return find(parent); function find(n) { if (ts.isToken(n) && n.pos === previousToken.end) { @@ -69391,7 +70782,7 @@ var ts; var child = children_3[_i]; var shouldDiveInChildNode = (child.pos <= previousToken.pos && child.end > previousToken.end) || (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { + if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) { return find(child); } } @@ -69413,10 +70804,10 @@ var ts; if (position < child.end) { var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || - !nodeHasTokens(child) || + !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { - var candidate = findRightmostChildNodeWithTokens(children, i); + var candidate = findRightmostChildNodeWithTokens(children, i, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } else { @@ -69426,7 +70817,7 @@ var ts; } ts.Debug.assert(startNode !== undefined || n.kind === 273 || ts.isJSDocCommentContainingNode(n)); if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, children.length); + var candidate = findRightmostChildNodeWithTokens(children, children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } } @@ -69440,16 +70831,16 @@ var ts; return n; } var children = n.getChildren(sourceFile); - var candidate = findRightmostChildNodeWithTokens(children, children.length); + var candidate = findRightmostChildNodeWithTokens(children, children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { var child = children[i]; if (isWhiteSpaceOnlyJsxText(child)) { ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); } - else if (nodeHasTokens(children[i])) { + else if (nodeHasTokens(children[i], sourceFile)) { return children[i]; } } @@ -69596,8 +70987,8 @@ var ts; } } ts.hasDocComment = hasDocComment; - function nodeHasTokens(n) { - return n.getWidth() !== 0; + function nodeHasTokens(n, sourceFile) { + return n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.getCombinedModifierFlags(node); @@ -69686,11 +71077,6 @@ var ts; return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { return isInComment(sourceFile, position, undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); @@ -69713,6 +71099,10 @@ var ts; return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createTextRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { return createTextChange(ts.createTextSpan(start, length), newText); } @@ -69790,6 +71180,60 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier) { + return ts.createImportDeclaration(undefined, undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + } + ts.makeImport = makeImport; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default") { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 71 ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (propSymbol && propSymbol.flags & 98304) { + ts.Debug.assert(!!(propSymbol.flags & 33554432)); + return propSymbol.target; + } + return propSymbol; + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + var NodeSet = (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; })(ts || (ts = {})); (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { @@ -70080,26 +71524,26 @@ var ts; return nameText; } ts.getUniqueName = getUniqueName; - function getRenameLocation(edits, renameFilename, name, isDeclaredBeforeUse) { + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { var delta = 0; var lastPos = -1; for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; ts.Debug.assert(fileName === renameFilename); - for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { - var change = textChanges_2[_b]; + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; var span = change.span, newText = change.newText; var index = newText.indexOf(name); if (index !== -1) { lastPos = span.start + delta + index; - if (!isDeclaredBeforeUse) { + if (!preferLastLocation) { return lastPos; } } delta += newText.length - span.length; } } - ts.Debug.assert(isDeclaredBeforeUse); + ts.Debug.assert(preferLastLocation); ts.Debug.assert(lastPos >= 0); return lastPos; } @@ -70628,20 +72072,22 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); pos = tag.tagName.end; switch (tag.kind) { - case 288: + case 292: processJSDocParameterTag(tag); break; - case 291: + case 295: processJSDocTemplateTag(tag); + pos = tag.end; break; - case 290: + case 294: processElement(tag.typeExpression); + pos = tag.end; break; - case 289: + case 293: processElement(tag.typeExpression); + pos = tag.end; break; } - pos = tag.end; } } if (pos !== docComment.end) { @@ -70864,7 +72310,7 @@ var ts; var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = ts.getSupportedExtensions(compilerOptions); + var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, false, compilerOptions, host, scriptPath); } @@ -70876,6 +72322,12 @@ var ts; return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json") : + extensions; + } function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { @@ -70900,13 +72352,15 @@ var ts; fragment = ""; } fragment = ts.normalizeSlashes(fragment); - fragment = ts.getDirectoryPath(fragment); + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } if (fragment === "") { fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); - var baseDirectory = ts.getDirectoryPath(absolutePath); + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (tryDirectoryExists(host, baseDirectory)) { var files = tryReadDirectory(host, baseDirectory, extensions, undefined, ["./*"]); @@ -70918,7 +72372,7 @@ var ts; if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0) { continue; } - var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json") ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } @@ -70943,7 +72397,7 @@ var ts; function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); @@ -70951,19 +72405,19 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_10 = function (name, kind) { + var _loop_12 = function (name, kind) { if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_10(name, kind); + _loop_12(name, kind); } } } } - var fragmentDirectory = containsSlash(fragment) ? ts.getDirectoryPath(fragment) : undefined; + var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { var ambientName = _d[_c]; result.push(nameAndKind(ambientName, "external module name")); @@ -70972,7 +72426,7 @@ var ts; if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_11 = function (moduleName) { + var _loop_13 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name")); @@ -70980,7 +72434,7 @@ var ts; }; for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { var moduleName = _f[_e]; - _loop_11(moduleName); + _loop_13(moduleName); } } if (!foundGlobal) { @@ -71013,11 +72467,12 @@ var ts; if (!parsed) { return undefined; } - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); var fragmentHasPath = containsSlash(fragment); - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; @@ -71163,13 +72618,6 @@ var ts; } return false; } - function normalizeAndPreserveTrailingSlash(path) { - if (ts.normalizeSlashes(path) === "./") { - return ""; - } - var norm = ts.normalizePath(path); - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; - } var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*"; } } - function getJSDocTypedefTagName(node) { - if (node.name) { - return node.name.text; - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 213) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71) { - return nameIdentifier.text; - } - } - } - return ""; - } - } function topLevelItems(root) { var topLevel = []; function recur(item) { @@ -76156,7 +77654,8 @@ var ts; case 238: case 273: case 236: - case 292: + case 296: + case 291: return true; case 154: case 153: @@ -76302,16 +77801,21 @@ var ts; (function (OrganizeImports) { function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(topLevelImportDecls); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; var ambientModuleBody = getModuleBlock(ambientModule); var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(ambientModuleImportDecls); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); - function organizeImportsWorker(oldImportDecls) { + function organizeImportsWorker(oldImportDecls, coalesce) { if (ts.length(oldImportDecls) === 0) { return; } @@ -76320,7 +77824,7 @@ var ts; var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + ? coalesce(importGroup) : importGroup; }); if (newImportDecls.length === 0) { @@ -76387,7 +77891,9 @@ var ts; } } function getExternalModuleName(specifier) { - return ts.isStringLiteralLike(specifier) ? specifier.text : undefined; + return specifier !== undefined && ts.isStringLiteralLike(specifier) + ? specifier.text + : undefined; } function coalesceImports(importGroup) { if (importGroup.length === 0) { @@ -76425,15 +77931,14 @@ var ts; } } newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); - var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { - return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || - compareIdentifiers(s1.name, s2.name); - }); + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); @@ -76470,22 +77975,65 @@ var ts; namedImports: namedImports, }; } - function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); - } } OrganizeImports.coalesceImports = coalesceImports; + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); + } function compareModuleSpecifiers(m1, m2) { var name1 = getExternalModuleName(m1); var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); var ts; @@ -76494,7 +78042,7 @@ var ts; var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) { + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); if (newPath !== undefined) { @@ -76506,25 +78054,16 @@ var ts; } ts.getEditsForFileRename = getEditsForFileRename; function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var cfg = program.getCompilerOptions().configFile; - if (!cfg) - return; - var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath); + var configFile = program.getCompilerOptions().configFile; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); if (oldFile) { - changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath); + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); } } - function getFilesEntry(cfg, fileName) { - var filesProp = ts.find(cfg.properties, function (prop) { - return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; - }); - var files = filesProp && filesProp.initializer; - return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined; - } function isRef(toUpdate) { return "fileName" in toUpdate; } - function getImportsToUpdate(program, oldFilePath) { + function getImportsToUpdate(program, oldFilePath, host) { var checker = program.getTypeChecker(); var result = []; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { @@ -76539,8 +78078,10 @@ var ts; var importStringLiteral = _e[_d]; if (checker.getSymbolAtLocation(importStringLiteral)) continue; - var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (ts.contains(resolved.failedLookupLocations, oldFilePath)) { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); } } @@ -76548,11 +78089,11 @@ var ts; return result; } function getPathUpdater(oldFilePath, newFilePath, host) { - var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); return function (oldPath) { if (!ts.pathIsRelative(oldPath)) return; - return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); }; } function createStringRange(node, sourceFile) { @@ -76572,7 +78113,27 @@ var ts; OutliningElementsCollector.collectElements = collectElements; function addNodeOutliningSpans(sourceFile, cancellationToken, out) { var depthRemaining = 40; - sourceFile.forEachChild(function walk(n) { + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports")); + } + } + function visitNonImportNode(n) { if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); @@ -76584,17 +78145,17 @@ var ts; out.push(span); depthRemaining--; if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { - walk(n.expression); - walk(n.thenStatement); + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); depthRemaining++; - walk(n.elseStatement); + visitNonImportNode(n.elseStatement); depthRemaining--; } else { - n.forEachChild(walk); + n.forEachChild(visitNonImportNode); } depthRemaining++; - }); + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -76609,7 +78170,7 @@ var ts; } if (!result[1]) { var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); - regions.push(createOutliningSpan(span, span, false, result[2] || "#region")); + regions.push(createOutliningSpan(span, "region", span, false, result[2] || "#region")); } else { var region = regions.pop(); @@ -76641,7 +78202,7 @@ var ts; break; case 3: combineAndAddMultipleSingleLineComments(); - out.push(createOutliningSpanFromBounds(pos, end)); + out.push(createOutliningSpanFromBounds(pos, end, "comment")); singleLineCommentCount = 0; break; default: @@ -76651,12 +78212,12 @@ var ts; combineAndAddMultipleSingleLineComments(); function combineAndAddMultipleSingleLineComments() { if (singleLineCommentCount > 1) { - out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment")); } } } - function createOutliningSpanFromBounds(pos, end) { - return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { @@ -76683,7 +78244,7 @@ var ts; return spanForNode(ts.findChildOfKind(tryStatement, 87, sourceFile)); } default: - return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code"); } case 239: return spanForNode(n.parent); @@ -76712,14 +78273,14 @@ var ts; return undefined; } var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); - return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + return createOutliningSpan(textSpan, "code", ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { if (hintSpan === void 0) { hintSpan = textSpan; } if (autoCollapse === void 0) { autoCollapse = false; } if (bannerText === void 0) { bannerText = "..."; } - return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); @@ -76899,13 +78460,13 @@ var ts; } function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_13 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_4 = _loop_13(start); + var state_4 = _loop_15(start); if (typeof state_4 === "object") return state_4.value; } @@ -77365,6 +78926,8 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 && symbol.parent.flags & 1536) { return undefined; } + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -77476,7 +79039,7 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_14 = function (declaration) { + var _loop_16 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -77490,7 +79053,7 @@ var ts; }; for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { var declaration = declarations_12[_b]; - var state_5 = _loop_14(declaration); + var state_5 = _loop_16(declaration); if (typeof state_5 === "object") return state_5.value; } @@ -77745,7 +79308,9 @@ var ts; program.getSemanticDiagnostics(sourceFile); var checker = program.getDiagnosticsProducingTypeChecker(); var diags = []; - if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))) { + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJavaScript(sourceFile); @@ -77794,9 +79359,31 @@ var ts; } } } - return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 213: + return statement.declarationList.declarations.some(function (decl) { + return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), true); + }); + case 215: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, true); + var kind = ts.getSpecialPropertyAssignmentKind(expression); + return kind === 1 || kind === 2; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } function importNameForConvertToDefaultImport(node) { switch (node.kind) { case 243: @@ -78458,7 +80045,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_15 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -78474,7 +80061,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_15(opt); + _loop_17(opt); } return options; } @@ -78847,6 +80434,7 @@ var ts; rule("NoSpaceAfterQuestionMark", 55, anyToken, [isNonJsxSameLineTokenContext], 8), rule("NoSpaceBeforeDot", anyToken, 23, [isNonJsxSameLineTokenContext], 8), rule("NoSpaceAfterDot", 23, anyToken, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBetweenImportParenInImportType", 91, 19, [isNonJsxSameLineTokenContext, isImportTypeContext], 8), rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8), rule("NoSpaceAfterUnaryPreincrementOperator", 43, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8), rule("NoSpaceAfterUnaryPredecrementOperator", 44, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8), @@ -79231,6 +80819,9 @@ var ts; function isArrowFunctionContext(context) { return context.contextNode.kind === 192; } + function isImportTypeContext(context) { + return context.contextNode.kind === 178; + } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10; } @@ -80412,7 +82003,7 @@ var ts; NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; })(NextTokenKind || (NextTokenKind = {})); function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { - var nextToken = ts.findNextToken(precedingToken, current); + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); if (!nextToken) { return 0; } @@ -80452,9 +82043,10 @@ var ts; } function getContainingList(node, sourceFile) { if (node.parent) { + var end = node.end; switch (node.parent.kind) { case 161: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); case 183: return node.parent.properties; case 182: @@ -80469,22 +82061,25 @@ var ts; case 163: case 158: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || + getListIfStartEndIsInListRange(node.parent.parameters, start, end); } case 234: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); case 187: case 186: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || + getListIfStartEndIsInListRange(node.parent.arguments, start, end); } case 232: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); case 246: case 250: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); + case 179: + case 180: + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); } } return undefined; @@ -80773,10 +82368,10 @@ var ts; return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { - return node.getEnd(); + return end; } - var end = node.getEnd(); var newEnd = ts.skipTrivia(sourceFile.text, end, true); return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) ? newEnd @@ -80797,7 +82392,8 @@ var ts; this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.deletedNodesInLists = []; + this.newFiles = []; + this.deletedNodesInLists = new ts.NodeSet(); this.classesWithNodesInsertedAtStart = ts.createMap(); } ChangeTracker.fromContext = function (context) { @@ -80840,32 +82436,12 @@ var ts; this.deleteNode(sourceFile, node); return this; } - var id = ts.getNodeId(node); - ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); - this.deletedNodesInLists[id] = true; - if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end, false); - if (nextToken && isSeparator(node, nextToken)) { - var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), false, true); - var nextElement = containingList[index + 1]; - var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), false, true); - this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - } - } - else { - var prev = containingList[index - 1]; - if (this.deletedNodesInLists[ts.getNodeId(prev)]) { - var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), false, true); - var end = getAdjustedEndPosition(sourceFile, node, {}); - this.deleteRange(sourceFile, { pos: pos, end: end }); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); - } - } - } + ts.Debug.assert(!this.deletedNodesInLists.has(node), "Deleting a node twice"); + this.deletedNodesInLists.add(node); + this.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); return this; }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { @@ -80894,10 +82470,13 @@ var ts; if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 26 ? next : undefined; + }; ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { - return this.replaceNode(sourceFile, oldNode, newNode, { - suffix: "," + this.newLineCharacter - }); + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } @@ -80927,7 +82506,8 @@ var ts; var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, false); - var text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter; + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { @@ -80997,28 +82577,50 @@ var ts; }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); - var prefix = ""; - var suffix = this.newLineCharacter; - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { - prefix = this.newLineCharacter; - if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { - suffix = ""; - } - } var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix }); + this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { + if (cls.members.length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); + return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + } + else { + return { prefix: "", suffix: this.newLineCharacter }; + } + } + else { + return { prefix: this.newLineCharacter, suffix: "" }; + } + }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { if (needSemicolonBetween(after, newNode)) { if (sourceFile.text.charCodeAt(after.end - 1) !== 59) { this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after)); + return endPosition; }; - ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; } @@ -81059,8 +82661,11 @@ var ts; this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } }; - ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { - var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); + }; + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); return this; @@ -81130,13 +82735,38 @@ var ts; } }); }; + ChangeTracker.prototype.finishTrailingCommaAfterDeletingNodesInList = function () { + var _this = this; + this.deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !_this.deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } + }); + }; ChangeTracker.prototype.getChanges = function (validate) { this.finishClassesWithNodesInsertedAtStart(); - return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + this.finishTrailingCommaAfterDeletingNodesInList(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); }; return ChangeTracker; }()); textChanges_3.ChangeTracker = ChangeTracker; + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), false, true); + } function getClassBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17, sourceFile).end, ts.findChildOfKind(cls, 18, sourceFile).end]; } @@ -81145,14 +82775,14 @@ var ts; function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; - var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); - var _loop_16 = function (i) { + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; for (var i = 0; i < normalized.length - 1; i++) { - _loop_16(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -81161,6 +82791,11 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter) { + var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -81495,10 +83130,11 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); - function getRefactorContextLength(context) { - return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); } - ts.getRefactorContextLength = getRefactorContextLength; + ts.getRefactorContextSpan = getRefactorContextSpan; })(ts || (ts = {})); var ts; (function (ts) { @@ -81563,7 +83199,7 @@ var ts; if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { if (!decl.typeParameters) { var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); - if (typeParameters) + if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19, sourceFile); @@ -81599,18 +83235,18 @@ var ts; } function transformJSDocType(node) { switch (node.kind) { - case 276: - case 277: - return ts.createTypeReferenceNode("any", ts.emptyArray); - case 280: - return transformJSDocOptionalType(node); - case 279: - return transformJSDocType(node.type); case 278: - return transformJSDocNullableType(node); + case 279: + return ts.createTypeReferenceNode("any", ts.emptyArray); case 282: - return transformJSDocVariadicType(node); + return transformJSDocOptionalType(node); case 281: + return transformJSDocType(node.type); + case 280: + return transformJSDocNullableType(node); + case 284: + return transformJSDocVariadicType(node); + case 283: return transformJSDocFunctionType(node); case 161: return transformJSDocTypeReference(node); @@ -81634,7 +83270,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 282 && index === node.parent.parameters.length - 1; + var isRest = node.type.kind === 284 && index === node.parent.parameters.length - 1; var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.createToken(24) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -81884,7 +83520,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242: - changes.replaceNode(importingFile, importNode, makeImport(importNode.name, undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, undefined, moduleSpecifier)); break; case 186: if (ts.isRequireCall(importNode, false)) { @@ -81945,7 +83581,7 @@ var ts; switch (expression.kind) { case 186: { if (ts.isRequireCall(expression, true)) { - changes.replaceNode(sourceFile, statement, makeImport(undefined, undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(undefined, undefined, expression.arguments[0])); } return false; } @@ -82010,23 +83646,26 @@ var ts; changes.deleteNode(sourceFile, assignment.parent); } else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + return true; } - changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); - return changedToDefaultExport; } } else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { convertNamedExport(sourceFile, assignment, changes, exports); } return false; - var _a; } function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { case 155: case 156: @@ -82041,6 +83680,7 @@ var ts; ts.Debug.assertNever(prop); } }); + return statements && [statements, false]; } function convertNamedExport(sourceFile, assignment, changes, exports) { var text = assignment.left.name.text; @@ -82056,26 +83696,6 @@ var ts; convertExportsPropertyAssignment(assignment, sourceFile, changes); } } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84), ts.createToken(79)]; - switch (exported.kind) { - case 191: - case 192: { - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 204: { - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 186: - if (ts.isRequireCall(exported, true)) { - return convertReExportAll(exported.arguments[0], checker); - } - default: - return [[ts.createExportAssignment(undefined, undefined, false, exported)], true]; - } - } function convertReExportAll(reExported, checker) { var moduleSpecifier = reExported.text; var moduleSymbol = checker.getSymbolAtLocation(reExported); @@ -82136,13 +83756,13 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [makeImport(undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(undefined, importSpecifiers, moduleSpecifier)]; } } case 180: { var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier), makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } @@ -82183,7 +83803,7 @@ var ts; if (!namedBindings) { needDefaultImport = true; } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; } function makeUniqueName(name, identifiers) { while (identifiers.original.has(name) || identifiers.additional.has(name)) { @@ -82221,17 +83841,9 @@ var ts; } function makeSingleImport(localName, propertyName, moduleSpecifier) { return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier) - : makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier) + : ts.makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); } - function makeImport(name, namedImports, moduleSpecifier) { - return makeImportDeclaration(name, namedImports, moduleSpecifier); - } - function makeImportDeclaration(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(undefined, undefined, importClause, moduleSpecifier); - } - codefix.makeImportDeclaration = makeImportDeclaration; function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); } @@ -82382,7 +83994,7 @@ var ts; function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken, preferences) { var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } @@ -82478,12 +84090,6 @@ var ts; return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); } } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js") : undefined; - }) || false; - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -82497,229 +84103,14 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { - var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(sourceFile); + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences); return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); }); return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var count = 0; - for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { - count++; - } - return count; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName); - } - } - } - function getNodeModulePathParts(fullPath) { - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1; - } - break; - case 1: - case 2: - if (state === 1 && fullPath.charAt(partStart + 1) === "@") { - state = 2; - } - else { - packageRootIndex = partEnd; - state = 3; - } - break; - case 3: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1; - } - else { - state = 3; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { var fromExistingImport = ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -82738,7 +84129,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences); for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) { var info = newImportInfos_1[_i]; addNew.push(getCodeActionForNewImport(ctx, info)); @@ -83154,7 +84545,23 @@ var ts; } function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + } + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; } function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { var stringTypeNode = ts.createKeywordTypeNode(137); @@ -83438,6 +84845,7 @@ var ts; ts.Diagnostics._0_is_declared_but_never_used.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -83448,9 +84856,13 @@ var ts; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start, undefined); }); + if (delDestructure.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, undefined); }); if (deletion.length) { result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } @@ -83461,35 +84873,66 @@ var ts; return result; }, fixIds: [fixIdPrefix, fixIdDelete], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var sourceFile = context.sourceFile; - var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); - switch (context.fixId) { - case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); - } - break; - case fixIdDelete: - var importDecl = tryGetFullImport(diag.file, diag.start); - if (importDecl) { - changes.deleteNode(sourceFile, importDecl); - } - else { - tryDeleteDeclaration(changes, sourceFile, token); - } - break; - default: - ts.Debug.fail(JSON.stringify(context.fixId)); - } - }); }, + getAllCodeActions: function (context) { + var deleted = new NodeSet(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var sourceFile = context.sourceFile; + var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: + if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); })) + break; + var importDecl = tryGetFullImport(diag.file, diag.start); + if (importDecl) { + changes.deleteNode(sourceFile, importDecl); + } + else { + if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) { + tryDeleteDeclaration(changes, sourceFile, token, deleted); + } + } + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, }); function tryGetFullImport(sourceFile, pos) { var startToken = ts.getTokenAtPosition(sourceFile, pos, false); return startToken.kind === 91 ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; } + function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) { + var startToken = ts.getTokenAtPosition(sourceFile, pos, false); + if (startToken.kind !== 17 || !ts.isObjectBindingPattern(startToken.parent)) + return false; + var decl = startToken.parent.parent; + switch (decl.kind) { + case 231: + tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors); + break; + case 148: + if (deletedAncestors) + deletedAncestors.add(decl); + changes.deleteNodeInList(sourceFile, decl); + break; + case 181: + if (deletedAncestors) + deletedAncestors.add(decl); + changes.deleteNode(sourceFile, decl); + break; + default: + return ts.Debug.assertNever(decl); + } + return true; + } function getToken(sourceFile, pos) { - var token = ts.findPrecedingToken(pos, sourceFile); + var token = ts.findPrecedingToken(pos, sourceFile, undefined, true); return token.kind === 22 ? ts.findPrecedingToken(pos - 1, sourceFile) : token; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { @@ -83512,38 +84955,45 @@ var ts; } return false; } - function tryDeleteDeclaration(changes, sourceFile, token) { + function tryDeleteDeclaration(changes, sourceFile, token, deletedAncestors) { switch (token.kind) { case 71: - tryDeleteIdentifier(changes, sourceFile, token); + tryDeleteIdentifier(changes, sourceFile, token, deletedAncestors); break; case 151: case 245: + if (deletedAncestors) + deletedAncestors.add(token.parent); changes.deleteNode(sourceFile, token.parent); break; default: - tryDeleteDefault(changes, sourceFile, token); + tryDeleteDefault(changes, sourceFile, token, deletedAncestors); } } - function tryDeleteDefault(changes, sourceFile, token) { + function tryDeleteDefault(changes, sourceFile, token, deletedAncestors) { if (ts.isDeclarationName(token)) { + if (deletedAncestors) + deletedAncestors.add(token.parent); changes.deleteNode(sourceFile, token.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + if (deletedAncestors) + deletedAncestors.add(token.parent.parent); changes.deleteNode(sourceFile, token.parent.parent); } } - function tryDeleteIdentifier(changes, sourceFile, identifier) { + function tryDeleteIdentifier(changes, sourceFile, identifier, deletedAncestors) { var parent = identifier.parent; switch (parent.kind) { case 231: - tryDeleteVariableDeclaration(changes, sourceFile, parent); + tryDeleteVariableDeclaration(changes, sourceFile, parent, deletedAncestors); break; case 147: - var typeParameters = parent.parent.typeParameters; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(parent.parent); if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); + var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; + var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1, false); + var nextToken = ts.getTokenAtPosition(sourceFile, end, false); ts.Debug.assert(previousToken.kind === 27); ts.Debug.assert(nextToken.kind === 29); changes.deleteNodeRange(sourceFile, previousToken, nextToken); @@ -83566,6 +85016,20 @@ var ts; changes.deleteNodeInList(sourceFile, parent); } break; + case 181: { + var pattern = parent.parent; + switch (pattern.kind) { + case 180: + changes.deleteNode(sourceFile, parent); + break; + case 179: + changes.deleteNodeInList(sourceFile, parent); + break; + default: + return ts.Debug.assertNever(pattern); + } + break; + } case 242: var importEquals = ts.getAncestor(identifier, 242); changes.deleteNode(sourceFile, importEquals); @@ -83600,7 +85064,7 @@ var ts; tryDeleteNamedImportBinding(changes, sourceFile, parent); break; default: - tryDeleteDefault(changes, sourceFile, identifier); + tryDeleteDefault(changes, sourceFile, identifier, deletedAncestors); break; } } @@ -83616,15 +85080,19 @@ var ts; changes.deleteNode(sourceFile, importDecl); } } - function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { + function tryDeleteVariableDeclaration(changes, sourceFile, varDecl, deletedAncestors) { switch (varDecl.parent.parent.kind) { case 219: { var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; if (forInitializer.declarations.length === 1) { + if (deletedAncestors) + deletedAncestors.add(forInitializer); changes.deleteNode(sourceFile, forInitializer); } else { + if (deletedAncestors) + deletedAncestors.add(varDecl); changes.deleteNodeInList(sourceFile, varDecl); } break; @@ -83633,6 +85101,8 @@ var ts; var forOfStatement = varDecl.parent.parent; ts.Debug.assert(forOfStatement.initializer.kind === 232); var forOfInitializer = forOfStatement.initializer; + if (deletedAncestors) + deletedAncestors.add(forOfInitializer.declarations[0]); changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); break; case 220: @@ -83641,13 +85111,124 @@ var ts; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { + if (deletedAncestors) + deletedAncestors.add(variableStatement); changes.deleteNode(sourceFile, variableStatement); } else { + if (deletedAncestors) + deletedAncestors.add(varDecl); changes.deleteNodeInList(sourceFile, varDecl); } } } + var NodeSet = (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, false); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + switch (container.kind) { + case 216: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + break; + } + case 218: + case 219: + changes.deleteNode(sourceFile, container); + break; + default: + if (ts.isBlock(statement.parent)) { + split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); + } + else { + changes.deleteNode(sourceFile, statement); + } + } + } + function shouldRemove(s) { + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 | 2)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 235: + case 236: + return true; + case 238: + return ts.getModuleInstanceState(s) !== 1; + case 237: + return ts.hasModifier(s, 2048); + } + } + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + ts.Debug.assert(index !== -1); + return arr.slice(index); + } + function split(arr, pred, cb) { + ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, false); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56, sourceFile).end, true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -83668,7 +85249,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 278) { + if (typeNode.kind === 280) { actions.push(fix(checker.getNullableType(type, 4096), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; @@ -83686,7 +85267,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 278 && fixId === fixIdNullable ? checker.getNullableType(type, 4096) : type; + var fixedType = typeNode.kind === 280 && fixId === fixIdNullable ? checker.getNullableType(type, 4096) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -84003,16 +85584,16 @@ var ts; } var token = ts.getTokenAtPosition(sourceFile, start, false); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, ts.returnTrue); }); return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var seenFunctions = ts.createMap(); + var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, false), err.code, program, cancellationToken, seenFunctions); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, false), err.code, program, cancellationToken, markSeen); }); }, }); @@ -84026,7 +85607,7 @@ var ts; return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 && token.kind !== 24) { return undefined; } @@ -84034,17 +85615,18 @@ var ts; switch (errorCode) { case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) { + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); return symbol.valueDeclaration; } + return undefined; } } var containingFunction = ts.getContainingFunction(token); @@ -84058,7 +85640,7 @@ var ts; return containingFunction; } case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { + if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); return param; @@ -84246,6 +85828,15 @@ var ts; case 185: inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); break; + case 231: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } default: return inferTypeFromContextualType(node, checker, usageContext); } @@ -84403,7 +85994,7 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2)); + return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, false, checker); @@ -84514,7 +86105,7 @@ var ts; var namespace = ts.getNamespaceDeclarationNode(node); var opts = context.program.getCompilerOptions(); var variations = []; - variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, undefined, node.moduleSpecifier))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(undefined, undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)))); } @@ -84668,6 +86259,243 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var compilerOptions = program.getCompilerOptions(); + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName); + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js") : undefined; + }) || false; + } + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); + } + } + } + function getNodeModulePathParts(fullPath) { + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1; + } + break; + case 1: + case 2: + if (state === 1 && fullPath.charAt(partStart + 1) === "@") { + state = 2; + } + else { + packageRootIndex = partEnd; + state = 3; + } + break; + case 3: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1; + } + else { + state = 3; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -84734,7 +86562,39 @@ var ts; } } function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, undefined, info.moduleSpecifier)); + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, undefined, info.moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, false); + ts.Debug.assert(token.kind === 91); + ts.Debug.assert(token.parent.kind === 178); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, true); + changes.replaceNode(sourceFile, importType, newTypeNode); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -84747,7 +86607,7 @@ var ts; var refactorName = "Extract Symbol"; refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -84804,7 +86664,7 @@ var ts; } extractSymbol.getAvailableActions = getAvailableActions; function getEditsForAction(context, actionName) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); if (parsedFunctionIndexMatch) { @@ -85741,8 +87601,8 @@ var ts; }); i_1++; } - if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { - for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { var typeParameterDecl = _b[_a]; var typeParameter = checker.getTypeAtLocation(typeParameterDecl); if (allTypeParameterUsages.has(typeParameter.id.toString())) { @@ -85759,7 +87619,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_17 = function (i) { + var _loop_19 = function (i) { var scopeUsages = usagesPerScope[i]; if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; @@ -85795,21 +87655,11 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_17(i); + _loop_19(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; - function hasTypeParameters(node) { - return ts.isDeclarationWithTypeParameters(node) && - node.typeParameters !== undefined && - node.typeParameters.length > 0; - } function isInGenericContext(node) { - for (; node; node = node.parent) { - if (hasTypeParameters(node)) { - return true; - } - } - return false; + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); } function recordTypeParameterUsages(type) { var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); @@ -86036,8 +87886,8 @@ var ts; var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition; - if (!getConvertibleFieldAtPosition(file, startPosition)) + var file = context.file; + if (!getConvertibleFieldAtPosition(context, file)) return undefined; return [{ name: actionName, @@ -86051,27 +87901,44 @@ var ts; }]; } function getEditsForAction(context, _actionName) { - var file = context.file, startPosition = context.startPosition; - var fieldInfo = getConvertibleFieldAtPosition(file, startPosition); + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context, file); if (!fieldInfo) return undefined; var isJS = ts.isSourceFileJavaScript(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration; + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); var isInClassLike = ts.isClassLike(container); + var modifierFlags = ts.getModifierFlags(declaration) & ~64; var accessorModifiers = isInClassLike - ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 ? getModifiers(isJS, isStatic, 114) : declaration.modifiers + ? !modifierFlags || modifierFlags & 8 + ? getModifiers(isJS, isStatic, 114) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined; var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112) : undefined; - updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container); + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); - var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); insertAccessor(changeTracker, file, getAccessor, declaration, container); - insertAccessor(changeTracker, file, setAccessor, declaration, container); + if (isReadonly) { + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } var edits = changeTracker.getChanges(); var renameFilename = file.fileName; - var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1; - var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, false); + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, ts.isParameter(declaration)); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function isConvertableName(name) { @@ -86091,23 +87958,31 @@ var ts; var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115) : undefined); return modifiers && ts.createNodeArray(modifiers); } - function getConvertibleFieldAtPosition(file, startPosition) { + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95; + } + function getConvertibleFieldAtPosition(context, file) { + var startPosition = context.startPosition, endPosition = context.endPosition; var node = ts.getTokenAtPosition(file, startPosition, false); var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); - var meaning = 28 | 32; - if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + var meaning = 28 | 32 | 64; + if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) + || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; - var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name); - var accessorName = createPropertyName(declaration.name.text, declaration.name); - ts.suppressLeadingAndTrailingTrivia(fieldName); - ts.suppressLeadingAndTrailingTrivia(declaration); + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file.text), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file.text) : name, declaration.name); return { isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), container: declaration.kind === 148 ? declaration.parent.parent : declaration.parent, + originalName: declaration.name, declaration: declaration, fieldName: fieldName, accessorName: accessorName, + renameAccessor: startWithUnderscore }; } function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { @@ -86124,16 +87999,11 @@ var ts; var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } - function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) { - var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer); - changeTracker.insertNodeAtClassStart(file, classLikeContainer, property); - changeTracker.deleteNodeInList(file, declaration); - } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); changeTracker.replacePropertyAssignment(file, declaration, assignment); } - function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) { + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { if (ts.isPropertyDeclaration(declaration)) { updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); } @@ -86141,18 +88011,626 @@ var ts; updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container); + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { ts.isParameterPropertyDeclaration(declaration) ? changeTracker.insertNodeAtClassStart(file, container, accessor) - : changeTracker.insertNodeAfter(file, declaration, accessor); + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + if (!constructor.body) + return; + var file = context.file, program = context.program, cancellationToken = context.cancellationToken; + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); }); + ts.forEach(referenceEntries, function (entry) { + var parent = entry.parent; + var accessorName = ts.createIdentifier(fieldName.text); + var node = ts.isBinaryExpression(parent) + ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) + : ts.isPropertyAccessExpression(parent) + ? ts.updatePropertyAccess(parent, parent.expression, accessorName) + : ts.Debug.fail("Unexpected write access token"); + changeTracker.replaceNode(file, parent, node); + }); } })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + return undefined; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getFirstAndLastStatementToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + if (range.pos > statements[startNodeIndex].getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + } + function doChange(oldFile, program, toMove, changes, host) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + function getStatementsToMove(context) { + var statements = context.file.statements; + var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var all = []; + var ranges = []; + var rangeToMove = statements.slice(first, afterLast); + ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { + for (var i = start; i < afterEnd; i++) + all.push(rangeToMove[i]); + ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); + }); + return { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 243: + return true; + case 242: + return !ts.hasModifier(node, 1); + case 213: + return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + if (importsFromNewFile) { + changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, true); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last; + changes.deleteNodeRange(sourceFile, first_1, last_3); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_20 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_21 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_21(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_20(sourceFile); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 243 ? i.moduleSpecifier + : i.kind === 242 ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default") { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path); + } + else { + ts.Debug.assert(!defaultImport); + var bindingElements = imports.map(function (i) { return ts.createBindingElement(undefined, undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2; } + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 243: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 242: + if (isUnused(importDecl.name)) { + changes.deleteNode(sourceFile, importDecl); + } + break; + case 231: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 245 ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.deleteNode(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.deleteNode(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.deleteNode(sourceFile, namedBindings); + } + else if (namedBindings.kind === 246) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.deleteNodeInList(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 71: + if (isUnused(name)) { + changes.deleteNode(sourceFile, name); + } + break; + case 180: + break; + case 179: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.deleteNode(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.deleteNode(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + function isInImport(decl) { + switch (decl.kind) { + case 242: + case 247: + case 244: + return true; + case 231: + return isVariableDeclarationInImport(decl); + case 181: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 243: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(undefined, undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 242: + return keep(i.name) ? i : undefined; + case 231: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 245) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 71: + return keep(name) ? name : undefined; + case 180: + return name; + case 179: { + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 233: + case 234: + case 238: + case 237: + case 236: + case 235: + case 242: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 233: + case 234: + case 238: + case 237: + case 236: + case 235: + case 242: + return cb(statement); + case 213: + return ts.forEach(statement.declarationList.declarations, cb); + case 215: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 + ? cb(statement) + : undefined; + } + } + } + function nameOfTopLevelDeclaration(d) { + return d.kind === 215 ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + return ts.isVariableDeclaration(d) ? d.parent.parent : d; + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(84)], d.modifiers); + switch (d.kind) { + case 233: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 234: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 213: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 238: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 237: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 236: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 235: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 242: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 215: + return ts.Debug.fail(); + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 233: + case 234: + return [decl.name.text]; + case 213: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 238: + case 237: + case 236: + case 235: + case 242: + return undefined; + case 215: + return ts.Debug.fail(); + default: + ts.Debug.assertNever(decl); + } + } + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var sourcemaps; (function (sourcemaps) { @@ -86439,7 +88917,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 275 || kid.kind > 293; }); + var child = ts.find(children, function (kid) { return kid.kind < 277 || kid.kind > 297; }); return child.kind < 145 ? child : child.getFirstToken(sourceFile); @@ -86504,7 +88982,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(294, nodes.pos, nodes.end, parent); + var list = createNode(298, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -86990,6 +89468,9 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -87019,9 +89500,18 @@ var ts; return ts.isString(info) ? undefined : info; }; HostCache.prototype.getRootFileNames = function () { - return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { - return ts.isString(entry) ? entry : entry.hostFileName; + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6) { + names.push(entry.hostFileName); + } + } }); + return names; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); @@ -87173,6 +89663,7 @@ var ts; } ts.createSourceFileLikeCache = createSourceFileLikeCache; function createLanguageService(host, documentRegistry, syntaxOnly) { + var _a; if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } if (syntaxOnly === void 0) { syntaxOnly = false; } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -87265,7 +89756,14 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: hostCache.getProjectReferences() + }; + program = ts.createProgram(options); hostCache = undefined; sourcemappedFileCache = createSourceFileLikeCache(host); program.getTypeChecker(); @@ -87413,6 +89911,11 @@ var ts; } return checker.getSymbolAtLocation(node); } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); + return file.getLineAndCharacterOfPosition(position); + } var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/gm; var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; function scanForSourcemapURL(fileName) { @@ -87480,7 +89983,8 @@ var ts; } function makeGetTargetOfMappedPosition(extract, create) { return getTargetOfMappedPosition; - function getTargetOfMappedPosition(input) { + function getTargetOfMappedPosition(input, original) { + if (original === void 0) { original = input; } var info = extract(input); if (ts.endsWith(info.fileName, ".d.ts")) { var file = program.getSourceFile(info.fileName); @@ -87495,12 +89999,12 @@ var ts; var newLoc = mapper.getOriginalPosition(info); if (newLoc === info) return input; - return getTargetOfMappedPosition(create(newLoc, input)); + return getTargetOfMappedPosition(create(newLoc, input, original), original); } return input; } } - var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({ containerKind: info.containerKind, containerName: info.containerName, fileName: newLoc.fileName, @@ -87509,10 +90013,12 @@ var ts; textSpan: { start: newLoc.position, length: info.textSpan.length - } + }, + originalFileName: original.fileName, + originalTextSpan: original.textSpan }); }); function getTargetOfMappedDeclarationFiles(infos) { - return ts.map(infos, getTargetOfMappedDeclarationInfo); + return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); }); } function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); @@ -87543,10 +90049,12 @@ var ts; textSpan: { start: newLoc.position, length: info.textSpan.length - } + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan }); }); function getTargetOfMappedImplementationLocations(infos) { - return ts.map(infos, getTargetOfMappedImplementationLocation); + return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); }); } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); @@ -87956,8 +90464,8 @@ var ts; getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: toLineColumnOffset }; - var _a; } ts.createLanguageService = createLanguageService; function getNameTable(sourceFile) { @@ -88013,20 +90521,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_6 = []; + var result_7 = []; var symbol = type.getProperty(name); if (type.flags & 131072) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_7.push(symbol); } }); - return result_6; + return result_7; } if (symbol) { - result_6.push(symbol); - return result_6; + result_7.push(symbol); + return result_7; } } return undefined; @@ -88074,7 +90582,7 @@ var ts; return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { - return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { @@ -88089,7 +90597,7 @@ var ts; return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } function spanInNextNode(node) { - return spanInNode(ts.findNextToken(node, node.parent)); + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); } function spanInNode(node) { if (node) { @@ -90074,7 +92582,7 @@ var ts; ProjectKind[ProjectKind["External"] = 2] = "External"; })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); function countEachFileTypes(infos) { - var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; + var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0, deferred: 0 }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; switch (info.scriptKind) { @@ -90092,6 +92600,9 @@ var ts; case 4: result.tsx += 1; break; + case 7: + result.deferred += 1; + break; } } return result; @@ -90148,7 +92659,7 @@ var ts; this.compilerOptions.allowNonTsExtensions = true; this.compilerOptions.allowJs = true; } - else if (hasExplicitListOfFiles || this.compilerOptions.allowJs) { + else if (hasExplicitListOfFiles || this.compilerOptions.allowJs || this.projectService.hasDeferredExtension()) { this.compilerOptions.allowNonTsExtensions = true; } this.languageServiceEnabled = !projectService.syntaxOnly; @@ -90215,6 +92726,9 @@ var ts; Project.prototype.getProjectVersion = function () { return this.projectStateVersion.toString(); }; + Project.prototype.getProjectReferences = function () { + return undefined; + }; Project.prototype.getScriptFileNames = function () { var _this = this; if (!this.rootFiles) { @@ -90280,6 +92794,9 @@ var ts; Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }; + Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) { + return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile); + }; Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; @@ -90620,6 +93137,7 @@ var ts; this.hasAddedorRemovedFiles = true; }; Project.prototype.updateGraph = function () { + var _a; this.resolutionCache.startRecordingFilesWithChangedResolutions(); var hasNewProgram = this.updateGraphWorker(); var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; @@ -90633,11 +93151,11 @@ var ts; if (hasNewProgram || changedFiles.length) { var result = void 0; var ambientModules = this.program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); - for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { - var sourceFile = _b[_a]; + for (var _b = 0, _c = this.program.getSourceFiles(); _b < _c.length; _b++) { + var sourceFile = _c[_b]; var unResolved = this.extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules); if (unResolved !== server.emptyArray) { - (_c = (result || (result = []))).push.apply(_c, unResolved); + (_a = (result || (result = []))).push.apply(_a, unResolved); } } this.lastCachedUnresolvedImportsList = result ? server.toDeduplicatedSortedArray(result) : server.emptyArray; @@ -90651,7 +93169,6 @@ var ts; this.projectProgramVersion++; } return !hasNewProgram; - var _c; }; Project.prototype.updateTypingFiles = function (typingFiles) { var _this = this; @@ -90746,8 +93263,8 @@ var ts; var sourceFiles = this.program.getSourceFiles(); var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; if (writeProjectFileNames) { - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var file = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var file = sourceFiles_8[_i]; strBuilder += "\t" + file.fileName + "\n"; } } @@ -90825,7 +93342,7 @@ var ts; } var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_18 = function (globalPluginName) { + var _loop_22 = function (globalPluginName) { if (!globalPluginName) return "continue"; if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) @@ -90836,7 +93353,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_18(globalPluginName); + _loop_22(globalPluginName); } } }; @@ -90846,15 +93363,18 @@ var ts; var log = function (message) { _this.projectService.logger.info(message); }; - for (var _i = 0, searchPaths_1 = searchPaths; _i < searchPaths_1.length; _i++) { - var searchPath = searchPaths_1[_i]; - var resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log); - if (resolvedModule) { - this.enableProxy(resolvedModule, pluginConfigEntry); - return; - } + var resolvedModule = ts.firstDefined(searchPaths, function (searchPath) { + return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log); + }); + if (resolvedModule) { + this.enableProxy(resolvedModule, pluginConfigEntry); } - this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); + else { + this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); + } + }; + Project.prototype.refreshDiagnostics = function () { + this.projectService.sendProjectsUpdatedInBackgroundEvent(); }; Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { try { @@ -90970,9 +93490,10 @@ var ts; server.InferredProject = InferredProject; var ConfiguredProject = (function (_super) { __extends(ConfiguredProject, _super); - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost) { + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.projectReferences = projectReferences; _this.externalProjectRefCount = 0; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); _this.enablePlugins(); @@ -90997,6 +93518,12 @@ var ts; ConfiguredProject.prototype.getConfigFilePath = function () { return server.asNormalizedPath(this.getProjectName()); }; + ConfiguredProject.prototype.getProjectReferences = function () { + return this.projectReferences; + }; + ConfiguredProject.prototype.updateReferences = function (refs) { + this.projectReferences = refs; + }; ConfiguredProject.prototype.enablePlugins = function () { var host = this.projectService.host; var options = this.getCompilationSettings(); @@ -91123,6 +93650,7 @@ var ts; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; server.ProjectInfoTelemetryEvent = "projectInfo"; + server.OpenFileInfoTelemetryEvent = "openFileInfo"; function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { var map = ts.createMap(); for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { @@ -91268,6 +93796,7 @@ var ts; function ProjectService(opts) { var _this = this; this.filenameToScriptInfo = ts.createMap(); + this.allJsFilesForOpenFileTelemetry = ts.createMap(); this.externalProjectToConfiguredProjectMap = ts.createMap(); this.externalProjects = []; this.inferredProjects = []; @@ -91436,11 +93965,13 @@ var ts; this.delayEnsureProjectForOpenFiles(); }; ProjectService.prototype.delayUpdateProjectGraphs = function (projects) { - for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { - var project = projects_2[_i]; - this.delayUpdateProjectGraph(project); + if (projects.length) { + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var project = projects_2[_i]; + this.delayUpdateProjectGraph(project); + } + this.delayEnsureProjectForOpenFiles(); } - this.delayEnsureProjectForOpenFiles(); }; ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) { ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); @@ -91521,7 +94052,6 @@ var ts; this.handleDeletedFile(info); } else if (!info.isScriptOpen()) { - ts.Debug.assert(info.containingProjects.length !== 0); info.delayReloadNonMixedContentFile(); this.delayUpdateProjectGraphs(info.containingProjects); } @@ -91610,7 +94140,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_19 = function (inferredProject) { + var _loop_23 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -91622,7 +94152,7 @@ var ts; }; for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_19(inferredProject); + _loop_23(inferredProject); } } return project; @@ -91814,13 +94344,16 @@ var ts; }); }; ProjectService.prototype.forEachConfigFileLocation = function (info, action) { + var _this = this; if (this.syntaxOnly) { return undefined; } ts.Debug.assert(this.openFiles.has(info.path)); var projectRootPath = this.openFiles.get(info.path); var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); - while (!projectRootPath || ts.containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames)) { + var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); }; + var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot(); + do { var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); @@ -91837,7 +94370,7 @@ var ts; break; } searchPath = parentPath; - } + } while (anySearchPathOk || isSearchPathInProjectRoot()); return undefined; }; ProjectService.prototype.getConfigFileNameForFile = function (info) { @@ -91918,7 +94451,8 @@ var ts; configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave + compileOnSave: parsedCommandLine.compileOnSave, + projectReferences: parsedCommandLine.projectReferences }; return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; }; @@ -91971,11 +94505,11 @@ var ts; return; } this.seenProjects.set(projectKey, true); - if (!this.eventHandler) { + if (!this.eventHandler || !this.host.createSHA256Hash) { return; } var data = { - projectId: this.host.createHash(projectKey), + projectId: this.host.createSHA256Hash(projectKey), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -92017,7 +94551,7 @@ var ts; var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); project.configFileSpecs = configFileSpecs; project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program", project); if (!lastFileExceededProgramSize) { @@ -92101,6 +94635,7 @@ var ts; var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; project.configFileSpecs = configFileSpecs; project.setProjectErrors(configFileErrors); + project.updateReferences(projectOptions.projectReferences); var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); if (lastFileExceededProgramSize) { project.disableLanguageService(lastFileExceededProgramSize); @@ -92200,7 +94735,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_20 = function (project) { + var _loop_24 = function (project) { if (project.languageServiceEnabled && !project.isOrphan() && !project.getCompilerOptions().preserveSymlinks && @@ -92216,7 +94751,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_20(project); + _loop_24(project); } } } @@ -92443,8 +94978,16 @@ var ts; } }); this.printProjects(); + this.telemetryOnOpenFile(info); return { configFileName: configFileName, configFileErrors: configFileErrors }; }; + ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) { + if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { + return; + } + var info = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path).checkJsDirective }; + this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } }); + }; ProjectService.prototype.closeClientFile = function (uncheckedFileName) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); if (info) { @@ -92453,13 +94996,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_21 = function (proj) { + var _loop_25 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_21(proj); + _loop_25(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -92559,7 +95102,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_22 = function (name) { + var _loop_26 = function (name) { var rule = this_2.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -92574,7 +95117,7 @@ var ts; } } if (rule.exclude) { - var _loop_23 = function (exclude) { + var _loop_28 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -92597,7 +95140,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_23(exclude); + _loop_28(exclude); } } else { @@ -92612,11 +95155,11 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_22(name); + _loop_26(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_24 = function (i) { + var _loop_27 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -92650,7 +95193,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_24(i); + _loop_27(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -92749,6 +95292,15 @@ var ts; this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); } }; + ProjectService.prototype.hasDeferredExtension = function () { + for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { + var extension = _a[_i]; + if (extension.scriptKind === 7) { + return true; + } + } + return false; + }; ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; return ProjectService; }()); @@ -92938,6 +95490,7 @@ var ts; } var Session = (function () { function Session(opts) { + var _a; var _this = this; this.changeSeq = 0; this.handlers = ts.createMapFromTemplate((_a = {}, @@ -93268,7 +95821,6 @@ var ts; }; this.projectService = new server.ProjectService(settings); this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); - var _a; } Session.prototype.sendRequestCompletedEvent = function (requestId) { this.event({ request_seq: requestId }, "requestCompleted"); @@ -93521,9 +96073,7 @@ var ts; if (simplifiedResult) { return this.mapDefinitionInfo(definitions, project); } - else { - return definitions; - } + return definitions.map(Session.mapToOriginalLocation); }; Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; @@ -93542,18 +96092,27 @@ var ts; textSpan: this.toLocationTextSpan(definitionAndBoundSpan.textSpan, scriptInfo) }; } - return definitionAndBoundSpan; + return __assign({}, definitionAndBoundSpan, { definitions: definitionAndBoundSpan.definitions.map(Session.mapToOriginalLocation) }); }; Session.prototype.mapDefinitionInfo = function (definitions, project) { var _this = this; return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); }); }; + Session.mapToOriginalLocation = function (def) { + if (def.originalFileName) { + ts.Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is"); + return __assign({}, def, { fileName: def.originalFileName, textSpan: def.originalTextSpan, targetFileName: def.fileName, targetTextSpan: def.textSpan }); + } + return def; + }; Session.prototype.toFileSpan = function (fileName, textSpan, project) { - var scriptInfo = project.getScriptInfo(fileName); + var ls = project.getLanguageService(); + var start = ls.toLineColumnOffset(fileName, textSpan.start); + var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan)); return { file: fileName, - start: scriptInfo.positionToLineOffset(textSpan.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) + start: { line: start.line + 1, offset: start.character + 1 }, + end: { line: end.line + 1, offset: end.character + 1 } }; }; Session.prototype.getTypeDefinition = function (args) { @@ -93579,9 +96138,7 @@ var ts; return _this.toFileSpan(fileName, textSpan, project); }); } - else { - return implementations; - } + return implementations.map(Session.mapToOriginalLocation); }; Session.prototype.getOccurrences = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; @@ -93882,7 +96439,8 @@ var ts; textSpan: _this.toLocationTextSpan(s.textSpan, scriptInfo_1), hintSpan: _this.toLocationTextSpan(s.hintSpan, scriptInfo_1), bannerText: s.bannerText, - autoCollapse: s.autoCollapse + autoCollapse: s.autoCollapse, + kind: s.kind }); }); } else { @@ -94413,10 +96971,16 @@ var ts; }; Session.prototype.mapTextChangesToCodeEditsUsingScriptinfo = function (textChanges, scriptInfo) { var _this = this; - return { - fileName: textChanges.fileName, - textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) - }; + ts.Debug.assert(!!textChanges.isNewFile === !scriptInfo); + if (scriptInfo) { + return { + fileName: textChanges.fileName, + textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }; + } + else { + return this.convertNewFileTextChangeToCodeEdit(textChanges); + } }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { @@ -94425,6 +96989,12 @@ var ts; newText: change.newText ? change.newText : "" }; }; + Session.prototype.convertNewFileTextChangeToCodeEdit = function (textChanges) { + ts.Debug.assert(textChanges.textChanges.length === 1); + var change = ts.first(textChanges.textChanges); + ts.Debug.assert(change.span.start === 0 && change.span.length === 0); + return { fileName: textChanges.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] }; + }; Session.prototype.getBraceMatching = function (args, simplifiedResult) { var _this = this; var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -96061,5 +98631,3 @@ var ts; ioSession.listen(); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); - -//# sourceMappingURL=tsserver.js.map diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 70f99eaa8d5..cbf39a2a48f 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -337,32 +337,36 @@ declare namespace ts { EnumMember = 272, SourceFile = 273, Bundle = 274, - JSDocTypeExpression = 275, - JSDocAllType = 276, - JSDocUnknownType = 277, - JSDocNullableType = 278, - JSDocNonNullableType = 279, - JSDocOptionalType = 280, - JSDocFunctionType = 281, - JSDocVariadicType = 282, - JSDocComment = 283, - JSDocTypeLiteral = 284, - JSDocTag = 285, - JSDocAugmentsTag = 286, - JSDocClassTag = 287, - JSDocParameterTag = 288, - JSDocReturnTag = 289, - JSDocTypeTag = 290, - JSDocTemplateTag = 291, - JSDocTypedefTag = 292, - JSDocPropertyTag = 293, - SyntaxList = 294, - NotEmittedStatement = 295, - PartiallyEmittedExpression = 296, - CommaListExpression = 297, - MergeDeclarationMarker = 298, - EndOfDeclarationMarker = 299, - Count = 300, + UnparsedSource = 275, + InputFiles = 276, + JSDocTypeExpression = 277, + JSDocAllType = 278, + JSDocUnknownType = 279, + JSDocNullableType = 280, + JSDocNonNullableType = 281, + JSDocOptionalType = 282, + JSDocFunctionType = 283, + JSDocVariadicType = 284, + JSDocComment = 285, + JSDocTypeLiteral = 286, + JSDocSignature = 287, + JSDocTag = 288, + JSDocAugmentsTag = 289, + JSDocClassTag = 290, + JSDocCallbackTag = 291, + JSDocParameterTag = 292, + JSDocReturnTag = 293, + JSDocTypeTag = 294, + JSDocTemplateTag = 295, + JSDocTypedefTag = 296, + JSDocPropertyTag = 297, + SyntaxList = 298, + NotEmittedStatement = 299, + PartiallyEmittedExpression = 300, + CommaListExpression = 301, + MergeDeclarationMarker = 302, + EndOfDeclarationMarker = 303, + Count = 304, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -388,10 +392,10 @@ declare namespace ts { FirstBinaryOperator = 27, LastBinaryOperator = 70, FirstNode = 145, - FirstJSDocNode = 275, - LastJSDocNode = 293, - FirstJSDocTagNode = 285, - LastJSDocTagNode = 293 + FirstJSDocNode = 277, + LastJSDocNode = 297, + FirstJSDocTagNode = 288, + LastJSDocTagNode = 297 } enum NodeFlags { None = 0, @@ -415,6 +419,7 @@ declare namespace ts { ThisNodeOrAnySubNodesHasError = 131072, HasAggregatedChildData = 262144, JSDoc = 2097152, + JsonFile = 16777216, BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, @@ -1149,7 +1154,7 @@ declare namespace ts { kind: SyntaxKind.NotEmittedStatement; } /** - * A list of comma-seperated expressions. This node is only created by transformations. + * A list of comma-separated expressions. This node is only created by transformations. */ interface CommaListExpression extends Expression { kind: SyntaxKind.CommaListExpression; @@ -1277,7 +1282,7 @@ declare namespace ts { block: Block; } type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; + type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; @@ -1534,6 +1539,19 @@ declare namespace ts { name?: Identifier; typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; } + interface JSDocCallbackTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocCallbackTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression: JSDocSignature; + } + interface JSDocSignature extends JSDocType, Declaration { + kind: SyntaxKind.JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + type: JSDocReturnTag | undefined; + } interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; @@ -1644,12 +1662,32 @@ declare namespace ts { } interface Bundle extends Node { kind: SyntaxKind.Bundle; + prepends: ReadonlyArray; sourceFiles: ReadonlyArray; } + interface InputFiles extends Node { + kind: SyntaxKind.InputFiles; + javascriptText: string; + declarationText: string; + } + interface UnparsedSource extends Node { + kind: SyntaxKind.UnparsedSource; + text: string; + } interface JsonSourceFile extends SourceFile { - jsonObject?: ObjectLiteralExpression; + statements: NodeArray; + } + interface TsConfigSourceFile extends JsonSourceFile { extendedSourceFiles?: string[]; } + interface JsonMinusNumericLiteral extends PrefixUnaryExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: SyntaxKind.MinusToken; + operand: NumericLiteral; + } + interface JsonObjectExpressionStatement extends ExpressionStatement { + expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral; + } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; getSourceFile(fileName: string): SourceFile | undefined; @@ -1705,12 +1743,19 @@ declare namespace ts { */ getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; + getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + } + interface ResolvedProjectReference { + commandLine: ParsedCommandLine; + sourceFile: SourceFile; } interface CustomTransformers { - /** Custom transformers to evaluate before built-in transformations. */ + /** Custom transformers to evaluate before built-in .js transformations. */ before?: TransformerFactory[]; - /** Custom transformers to evaluate after built-in transformations. */ + /** Custom transformers to evaluate after built-in .js transformations. */ after?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .d.ts transformations. */ + afterDeclarations?: TransformerFactory[]; } interface SourceMapSpan { /** Line number in the .js file. */ @@ -1853,7 +1898,9 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + GenerateNamesForShadowedTypeParams = 4, UseStructuralFallback = 8, + ForbidIndexedAccessSymbolReferences = 16, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, UseOnlyExternalAliasing = 128, @@ -2217,6 +2264,7 @@ declare namespace ts { objectType: Type; indexType: Type; constraint?: Type; + simplified?: Type; } type TypeVariable = TypeParameter | IndexedAccessType; interface IndexType extends InstantiableType { @@ -2251,7 +2299,7 @@ declare namespace ts { Construct = 1 } interface Signature { - declaration?: SignatureDeclaration; + declaration?: SignatureDeclaration | JSDocSignature; typeParameters?: TypeParameter[]; parameters: Symbol[]; } @@ -2274,7 +2322,9 @@ declare namespace ts { AlwaysStrict = 64, PriorityImpliesCombination = 28 } - interface JsFileExtensionInfo { + /** @deprecated Use FileExtensionInfo instead. */ + type JsFileExtensionInfo = FileExtensionInfo; + interface FileExtensionInfo { extension: string; isMixedContent: boolean; scriptKind?: ScriptKind; @@ -2322,7 +2372,17 @@ declare namespace ts { interface PluginImport { name: string; } - type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined; + interface ProjectReference { + /** A normalized path on disk */ + path: string; + /** The path as the user originally wrote it */ + originalPath?: string; + /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ + prepend?: boolean; + /** True if it is intended that this reference form a circularity */ + circular?: boolean; + } + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -2378,6 +2438,7 @@ declare namespace ts { project?: string; reactNamespace?: string; jsxFactory?: string; + composite?: boolean; removeComments?: boolean; rootDir?: string; rootDirs?: string[]; @@ -2393,11 +2454,12 @@ declare namespace ts { suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; traceResolution?: boolean; + resolveJsonModule?: boolean; types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; esModuleInterop?: boolean; - [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; + [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; } interface TypeAcquisition { enableAutoDiscovery?: boolean; @@ -2437,7 +2499,12 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, - JSON = 6 + JSON = 6, + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + Deferred = 7 } enum ScriptTarget { ES3 = 0, @@ -2447,6 +2514,7 @@ declare namespace ts { ES2017 = 4, ES2018 = 5, ESNext = 6, + JSON = 100, Latest = 6 } enum LanguageVariant { @@ -2458,6 +2526,7 @@ declare namespace ts { options: CompilerOptions; typeAcquisition?: TypeAcquisition; fileNames: string[]; + projectReferences?: ReadonlyArray; raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; @@ -2469,8 +2538,17 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; + projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } + interface CreateProgramOptions { + rootNames: ReadonlyArray; + options: CompilerOptions; + projectReferences?: ReadonlyArray; + host?: CompilerHost; + oldProgram?: Program; + configFileParsingDiagnostics?: ReadonlyArray; + } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2561,6 +2639,7 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; + readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files @@ -2918,10 +2997,11 @@ declare namespace ts { readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** - * This should be cryptographically secure. * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) */ createHash?(data: string): string; + /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */ + createSHA256Hash?(data: string): string; getMemoryUsage?(): number; exit(exitCode?: number): void; realpath?(path: string): string; @@ -3298,6 +3378,8 @@ declare namespace ts { function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; + function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag; + function isJSDocSignature(node: Node): node is JSDocSignature; } declare namespace ts { /** @@ -3423,6 +3505,8 @@ declare namespace ts { function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; + function createStringLiteral(text: string): StringLiteral; + function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ @@ -3727,8 +3811,10 @@ declare namespace ts { function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; function createCommaList(elements: ReadonlyArray): CommaListExpression; function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; - function createBundle(sourceFiles: ReadonlyArray): Bundle; - function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle; + function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createUnparsedSourceFile(text: string): UnparsedSource; + function createInputFiles(javascript: string, declaration: string): InputFiles; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression; function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression; @@ -3792,6 +3878,7 @@ declare namespace ts { function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function moveSyntheticComments(node: T, original: Node): T; /** * Gets the constant value to emit for an expression. */ @@ -3935,6 +4022,7 @@ declare namespace ts { * @param configFileParsingDiagnostics - error during config file parsing * @returns A 'Program' object. */ + function createProgram(createProgramOptions: CreateProgramOptions): Program; function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; } declare namespace ts { @@ -4074,7 +4162,6 @@ declare namespace ts { function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; } declare namespace ts { - type DiagnosticReporter = (diagnostic: Diagnostic) => void; type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; @@ -4137,15 +4224,6 @@ declare namespace ts { /** Compiler options */ options: CompilerOptions; } - /** - * Reports config file diagnostics - */ - interface ConfigFileDiagnosticsReporter { - /** - * Reports unrecoverable error when parsing config file - */ - onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; - } /** * Host to create watch with config file */ @@ -4192,6 +4270,26 @@ declare namespace ts { } declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors + */ + interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter { + getCurrentDirectory(): string; + } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4213,7 +4311,7 @@ declare namespace ts { * Read tsconfig.json file * @param fileName The path to the config file */ - function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile; + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile; /** * Convert the json syntax tree into the json value */ @@ -4225,7 +4323,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; /** * Parse the contents of a config file (tsconfig.json). * @param jsonNode The contents of the config file to parse @@ -4233,7 +4331,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -4252,7 +4350,7 @@ declare namespace ts { getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; getFullStart(): number; getEnd(): number; - getWidth(sourceFile?: SourceFile): number; + getWidth(sourceFile?: SourceFileLike): number; getFullWidth(): number; getLeadingTriviaWidth(sourceFile?: SourceFile): number; getFullText(sourceFile?: SourceFile): string; @@ -4364,6 +4462,7 @@ declare namespace ts { getScriptKind?(fileName: string): ScriptKind; getScriptVersion(fileName: string): string; getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; + getProjectReferences?(): ReadonlyArray | undefined; getLocalizedDiagnosticMessages?(): any; getCancellationToken?(): HostCancellationToken; getCurrentDirectory(): string; @@ -4378,6 +4477,7 @@ declare namespace ts { fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getDirectories?(directoryName: string): string[]; /** @@ -4393,6 +4493,7 @@ declare namespace ts { readonly includeCompletionsForModuleExports?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly allowTextChangesInNewFiles?: boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -4441,6 +4542,7 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; + toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; @@ -4465,9 +4567,10 @@ declare namespace ts { fileName: string; } type OrganizeImportsScope = CombinedCodeFixScope; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; interface GetCompletionsAtPositionOptions extends UserPreferences { /** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */ - triggerCharacter?: string; + triggerCharacter?: CompletionsTriggerCharacter; /** @deprecated Use includeCompletionsForModuleExports */ includeExternalModuleExports?: boolean; /** @deprecated Use includeCompletionsWithInsertText */ @@ -4534,6 +4637,7 @@ declare namespace ts { interface FileTextChanges { fileName: string; textChanges: TextChange[]; + isNewFile?: boolean; } interface CodeAction { /** Description of the code action to display in the UI of the editor */ @@ -4620,6 +4724,12 @@ declare namespace ts { interface DocumentSpan { textSpan: TextSpan; fileName: string; + /** + * If the span represents a location that was remapped (e.g. via a .d.ts.map file), + * then the original filename and span will be specified here + */ + originalTextSpan?: TextSpan; + originalFileName?: string; } interface RenameLocation extends DocumentSpan { } @@ -4717,9 +4827,7 @@ declare namespace ts { insertSpaceBeforeTypeAnnotation?: boolean; indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } - interface DefinitionInfo { - fileName: string; - textSpan: TextSpan; + interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; containerKind: ScriptElementKind; @@ -4865,6 +4973,20 @@ declare namespace ts { * the 'Collapse to Definitions' command is invoked. */ autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + enum OutliningSpanKind { + /** Single or multi-line comments */ + Comment = "comment", + /** Sections marked by '// #region' and '// #endregion' comments */ + Region = "region", + /** Declarations and expressions */ + Code = "code", + /** Contiguous blocks of import declarations */ + Imports = "imports" } enum OutputFileType { JavaScript = 0, @@ -4988,7 +5110,9 @@ declare namespace ts { /** * */ - jsxAttribute = "JSX attribute" + jsxAttribute = "JSX attribute", + /** String literal */ + string = "string" } enum ScriptElementKindModifier { none = "", @@ -5348,6 +5472,7 @@ declare namespace ts.server { configHasFilesProperty: boolean; configHasIncludeProperty: boolean; configHasExcludeProperty: boolean; + projectReferences: ReadonlyArray | undefined; /** * these fields can be present in the project file */ @@ -5587,6 +5712,10 @@ declare namespace ts.server.protocol { * the 'Collapse to Definitions' command is invoked. */ autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; } /** * Response to OutliningSpansRequest request. @@ -6318,7 +6447,7 @@ declare namespace ts.server.protocol { /** * The host's additional supported .js file extensions */ - extraFileExtensions?: JsFileExtensionInfo[]; + extraFileExtensions?: FileExtensionInfo[]; } /** * Configure request; value of command field is "configure". Specifies @@ -6682,6 +6811,7 @@ declare namespace ts.server.protocol { command: CommandTypes.Formatonkey; arguments: FormatOnKeyRequestArgs; } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; /** * Arguments for completions messages. */ @@ -6690,7 +6820,7 @@ declare namespace ts.server.protocol { * Optional prefix to apply to possible completions. */ prefix?: string; - triggerCharacter?: string; + triggerCharacter?: CompletionsTriggerCharacter; /** * @deprecated Use UserPreferences.includeCompletionsForModuleExports */ @@ -7470,6 +7600,7 @@ declare namespace ts.server.protocol { */ readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly allowTextChangesInNewFiles?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -7523,6 +7654,7 @@ declare namespace ts.server.protocol { project?: string; reactNamespace?: string; removeComments?: boolean; + references?: ProjectReference[]; rootDir?: string; rootDirs?: string[]; skipLibCheck?: boolean; @@ -7535,6 +7667,7 @@ declare namespace ts.server.protocol { suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget | ts.ScriptTarget; traceResolution?: boolean; + resolveJsonModule?: boolean; types?: string[]; /** Paths used to used to compute primary types search locations */ typeRoots?: string[]; @@ -7633,7 +7766,7 @@ declare namespace ts.server { enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray): void; attach(projectService: ProjectService): void; onProjectClosed(p: Project): void; - readonly globalTypingsCacheLocation: string; + readonly globalTypingsCacheLocation: string | undefined; } const nullTypingsInstaller: ITypingsInstaller; } @@ -7710,7 +7843,7 @@ declare namespace ts.server { private readonly cancellationToken; isNonTsProject(): boolean; isJsOnlyProject(): boolean; - static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {}; + static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined; isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptions): Promise; private readonly typingsCache; @@ -7718,6 +7851,7 @@ declare namespace ts.server { getCompilerOptions(): CompilerOptions; getNewLine(): string; getProjectVersion(): string; + getProjectReferences(): ReadonlyArray | undefined; getScriptFileNames(): string[]; private getOrCreateScriptInfoAndAttachToProject; getScriptKind(fileName: string): ScriptKind; @@ -7731,6 +7865,7 @@ declare namespace ts.server { readFile(fileName: string): string | undefined; fileExists(file: string): boolean; resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[]; + getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations; resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists(path: string): boolean; getDirectories(path: string): string[]; @@ -7784,13 +7919,15 @@ declare namespace ts.server { private detachScriptInfoFromProject; private addMissingFileWatcher; private isWatchedMissingFile; - getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; getScriptInfo(uncheckedFileName: string): ScriptInfo; filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; protected enableGlobalPlugins(): void; protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + refreshDiagnostics(): void; private enableProxy; } /** @@ -7817,6 +7954,7 @@ declare namespace ts.server { */ class ConfiguredProject extends Project { compileOnSaveEnabled: boolean; + private projectReferences; private typeAcquisition; private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; @@ -7829,6 +7967,8 @@ declare namespace ts.server { */ updateGraph(): boolean; getConfigFilePath(): NormalizedPath; + getProjectReferences(): ReadonlyArray | undefined; + updateReferences(refs: ReadonlyArray | undefined): void; enablePlugins(): void; /** * Get the errors that dont have any file name associated @@ -7864,6 +8004,7 @@ declare namespace ts.server { const ConfigFileDiagEvent = "configFileDiag"; const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; const ProjectInfoTelemetryEvent = "projectInfo"; + const OpenFileInfoTelemetryEvent = "openFileInfo"; interface ProjectsUpdatedInBackgroundEvent { eventName: typeof ProjectsUpdatedInBackgroundEvent; data: { @@ -7912,6 +8053,18 @@ declare namespace ts.server { /** TypeScript version used by the server. */ readonly version: string; } + /** + * Info that we may send about a file that was just opened. + * Info about a file will only be sent once per session, even if the file changes in ways that might affect the info. + * Currently this is only sent for '.js' files. + */ + interface OpenFileInfoTelemetryEvent { + readonly eventName: typeof OpenFileInfoTelemetryEvent; + readonly data: OpenFileInfoTelemetryEventData; + } + interface OpenFileInfoTelemetryEventData { + readonly info: OpenFileInfo; + } interface ProjectInfoTypeAcquisitionData { readonly enable: boolean; readonly include: boolean; @@ -7923,8 +8076,12 @@ declare namespace ts.server { readonly ts: number; readonly tsx: number; readonly dts: number; + readonly deferred: number; } - type ProjectServiceEvent = ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent; + interface OpenFileInfo { + readonly checkJs: boolean; + } + type ProjectServiceEvent = ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; interface SafeList { [name: string]: { @@ -7947,7 +8104,7 @@ declare namespace ts.server { formatCodeOptions: FormatCodeSettings; preferences: UserPreferences; hostInfo: string; - extraFileExtensions?: JsFileExtensionInfo[]; + extraFileExtensions?: FileExtensionInfo[]; } interface OpenConfiguredProjectResult { configFileName?: NormalizedPath; @@ -7975,6 +8132,7 @@ declare namespace ts.server { * Container of all known scripts */ private readonly filenameToScriptInfo; + private readonly allJsFilesForOpenFileTelemetry; /** * maps external project file name to list of config files that were the part of this project */ @@ -8043,7 +8201,6 @@ declare namespace ts.server { updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; private delayEnsureProjectForOpenFiles; private delayUpdateProjectGraph; - private sendProjectsUpdatedInBackgroundEvent; private delayUpdateProjectGraphs; setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void; findProject(projectName: string): Project | undefined; @@ -8180,6 +8337,7 @@ declare namespace ts.server { openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; private findExternalProjectContainingOpenScriptInfo; openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; + private telemetryOnOpenFile; /** * Close file whose contents is managed by the client * @param filename is absolute pathname @@ -8195,6 +8353,7 @@ declare namespace ts.server { resetSafeList(): void; applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; openExternalProject(proj: protocol.ExternalProject): void; + hasDeferredExtension(): boolean; } } declare namespace ts.server { @@ -8280,6 +8439,7 @@ declare namespace ts.server { private getDefinition; private getDefinitionAndBoundSpan; private mapDefinitionInfo; + private static mapToOriginalLocation; private toFileSpan; private getTypeDefinition; private getImplementation; @@ -8353,6 +8513,7 @@ declare namespace ts.server { private mapTextChangesToCodeEdits; private mapTextChangesToCodeEditsUsingScriptinfo; private convertTextChangeToCodeEdit; + private convertNewFileTextChangeToCodeEdit; private getBraceMatching; private getDiagnosticsForProject; getCanonicalFileName(fileName: string): string; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 96f58eb3c2c..ae049cd4143 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -350,38 +350,42 @@ var ts; // Top-level nodes SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile"; SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 275] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 276] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 277] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 278] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 279] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 280] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 281] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 282] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 283] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 284] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 285] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 286] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 287] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 288] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 289] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 290] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 291] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 292] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 293] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 294] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 295] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 296] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 297] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 298] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 299] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 300] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 301] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 302] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 303] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 304] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -408,10 +412,10 @@ var ts; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 277] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 297] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 288] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 297] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -451,6 +455,7 @@ var ts; NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; @@ -513,10 +518,9 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; // Flags - GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; @@ -591,9 +595,9 @@ var ts; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; @@ -885,6 +889,8 @@ var ts; TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType"; TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive"; /* @internal */ + TypeFlags[TypeFlags["UnionOfUnitTypes"] = 268435456] = "UnionOfUnitTypes"; + /* @internal */ TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; @@ -920,6 +926,8 @@ var ts; TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit"; /* @internal */ + TypeFlags[TypeFlags["NotUnit"] = 8374815] = "NotUnit"; + /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening"; /* @internal */ TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags"; @@ -1072,6 +1080,11 @@ var ts; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -1082,6 +1095,7 @@ var ts; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; @@ -1894,8 +1908,8 @@ var ts; } ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ - function findIndex(array, predicate) { - for (var i = 0; i < array.length; i++) { + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -1903,6 +1917,15 @@ var ts; return -1; } ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; /** * Returns the first truthy result of `callback`, or else fails. * This is like `forEach`, but never returns undefined. @@ -2255,6 +2278,24 @@ var ts; return false; } ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; function concatenate(array1, array2) { if (!some(array2)) return array1; @@ -2498,6 +2539,23 @@ var ts; return to; } ts.addRange = addRange; + /** + * Appends a range of value to begin of an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + function prependRange(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + to.unshift.apply(to, from); + return to; + } + ts.prependRange = prependRange; /** * @return Whether the value was added. */ @@ -2747,17 +2805,18 @@ var ts; } ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { + var _a; var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { result.push(map ? map(value) : value); } return result; - var _b; } ts.arrayFrom = arrayFrom; function forEachEntry(map, callback) { + var _a; var iterator = map.entries(); - for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { var key = pair[0], value = pair[1]; var result = callback(value, key); if (result) { @@ -2765,19 +2824,18 @@ var ts; } } return undefined; - var _b; } ts.forEachEntry = forEachEntry; function forEachKey(map, callback) { + var _a; var iterator = map.keys(); - for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { var result = callback(key); if (result) { return result; } } return undefined; - var _b; } ts.forEachKey = forEachKey; function copyEntries(source, target) { @@ -3334,11 +3392,11 @@ var ts; comparer(a[key], b[key]); } ts.compareProperties = compareProperties; - function getDiagnosticFileName(diagnostic) { - return diagnostic.file ? diagnostic.file.fileName : undefined; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; } function compareDiagnostics(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -3370,106 +3428,6 @@ var ts; // We still have one chain remaining. The shorter chain should come first. return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; } - function normalizeSlashes(path) { - return path.replace(/\\/g, "/"); - } - ts.normalizeSlashes = normalizeSlashes; - /** - * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") - */ - function getRootLength(path) { - if (path.charCodeAt(0) === 47 /* slash */) { - if (path.charCodeAt(1) !== 47 /* slash */) - return 1; - var p1 = path.indexOf("/", 2); - if (p1 < 0) - return 2; - var p2 = path.indexOf("/", p1 + 1); - if (p2 < 0) - return p1 + 1; - return p2 + 1; - } - if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) - return 3; - } - // Per RFC 1738 'file' URI schema has the shape file:/// - // if is omitted then it is assumed that host value is 'localhost', - // however slash after the omitted is not removed. - // file:///folder1/file1 - this is a correct URI - // file://folder2/file2 - this is an incorrect URI - if (path.lastIndexOf("file:///", 0) === 0) { - return "file:///".length; - } - var idx = path.indexOf("://"); - if (idx !== -1) { - return idx + "://".length; - } - return 0; - } - ts.getRootLength = getRootLength; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var directorySeparatorCharCode = 47 /* slash */; - function getNormalizedParts(normalizedSlashedPath, rootLength) { - var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); - var normalized = []; - for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { - var part = parts_1[_i]; - if (part !== ".") { - if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { - normalized.pop(); - } - else { - // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, - // e.g. "path//file.ts". Drop these before re-joining the parts. - if (part) { - normalized.push(part); - } - } - } - } - return normalized; - } - function normalizePath(path) { - return normalizePathAndParts(path).path; - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - var root = path.substr(0, rootLength); - var parts = getNormalizedParts(path, rootLength); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - /** A path ending with '/' refers to a directory only, never a file. */ - function pathEndsWithDirectorySeparator(path) { - return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; - } - ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; - function getDirectoryPath(path) { - return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function isUrl(path) { - return path && !isRootedDiskPath(path) && stringContains(path, "://"); - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0 /* ES3 */; } @@ -3501,6 +3459,10 @@ var ts; : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; } @@ -3521,202 +3483,455 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + // + // Paths + // + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ function isRootedDiskPath(path) { - return path && getRootLength(path) !== 0; + return getEncodedRootLength(path) > 0; } ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); } ts.convertToRelativePath = convertToRelativePath; - function normalizedPathComponents(path, rootLength) { - var normalizedParts = getNormalizedParts(path, rootLength); - return [path.substr(0, rootLength)].concat(normalizedParts); + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); } - function getNormalizedPathComponents(path, currentDirectory) { - path = normalizeSlashes(path); + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); var rootLength = getRootLength(path); - if (rootLength === 0) { - // If the path is not rooted it is relative to current directory - path = combinePaths(normalizeSlashes(currentDirectory), path); - rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); } - return normalizedPathComponents(path, rootLength); + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); } ts.getNormalizedPathComponents = getNormalizedPathComponents; function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); } ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getNormalizedPathFromPathComponents(pathComponents) { - if (pathComponents && pathComponents.length) { - return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); - } + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + if (pathComponents.length === 1) + return root; + return root + pathComponents.slice(1).join(ts.directorySeparator); } - ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; - function getNormalizedPathComponentsOfUrl(url) { - // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ - // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] - var urlLength = url.length; - // Initial root length is http:// part - var rootLength = url.indexOf("://") + "://".length; - while (rootLength < urlLength) { - // Consume all immediate slashes in the protocol - // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// - if (url.charCodeAt(rootLength) === 47 /* slash */) { - rootLength++; - } - else { - // non slash character means we continue proceeding to next component of root search + ts.getPathFromPathComponents = getPathFromPathComponents; + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) break; - } } - // there are no parts after http:// just return current string as the pathComponent - if (rootLength === urlLength) { - return [url]; + if (start === 0) { + return toComponents; } - // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) - var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); - if (indexOfNextSlash !== -1) { - // Found the "/" after the website.com so the root is length of http://www.website.com/ - // and get components after the root normally like any other folder components - rootLength = indexOfNextSlash + 1; - return normalizedPathComponents(url, rootLength); - } - else { - // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" - // eg. if url passed in was http://website.com we want to use root as [http://website.com/] - // so that other path manipulations will be correct and it can be merged with relative paths correctly - return [url + ts.directorySeparator]; + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); } + return [""].concat(relative, components); } - function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { - if (isUrl(pathOrUrl)) { - return getNormalizedPathComponentsOfUrl(pathOrUrl); - } - else { - return getNormalizedPathComponents(pathOrUrl, currentDirectory); - } + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] - directoryComponents.pop(); + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; } - // Find the component that differs - var joinStartIndex; - for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { - break; - } - } - // Get the relative path - if (joinStartIndex) { - var relativePath = ""; - var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); - for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (directoryComponents[joinStartIndex] !== "") { - relativePath = relativePath + ".." + ts.directorySeparator; - } - } - return relativePath + relativePathComponents.join(ts.directorySeparator); - } - // Cant find the relative path, get the absolute path - var absolutePath = getNormalizedPathFromPathComponents(pathComponents); - if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { - absolutePath = "file:///" + absolutePath; - } - return absolutePath; + return getPathFromPathComponents(pathComponents); } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function getRelativePath(path, directoryPath, getCanonicalFileName) { - var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ensurePathIsRelative(relativePath); + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path; } - ts.getRelativePath = getRelativePath; - function ensurePathIsRelative(path) { - return !pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsRelative = ensurePathIsRelative; - function getBaseFileName(path) { - if (path === undefined) { - return undefined; - } - var i = path.lastIndexOf(ts.directorySeparator); - return i < 0 ? path : path.substring(i + 1); + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; } ts.getBaseFileName = getBaseFileName; - function combinePaths(path1, path2) { - if (!(path1 && path1.length)) - return path2; - if (!(path2 && path2.length)) - return path1; - if (getRootLength(path2) !== 0) - return path2; - if (path1.charAt(path1.length - 1) === ts.directorySeparator) - return path1 + path2; - return path1 + ts.directorySeparator + path2; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; } ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function removeTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) === ts.directorySeparator) { + if (hasTrailingDirectorySeparator(path)) { return path.substr(0, path.length - 1); } return path; } ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; function ensureTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) !== ts.directorySeparator) { + if (!hasTrailingDirectorySeparator(path)) { return path + ts.directorySeparator; } return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - function comparePaths(a, b, currentDirectory, ignoreCase) { + function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0 /* EqualTo */; if (a === undefined) return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; - a = removeTrailingDirectorySeparator(a); - b = removeTrailingDirectorySeparator(b); - var aComponents = getNormalizedPathComponents(a, currentDirectory); - var bComponents = getNormalizedPathComponents(b, currentDirectory); + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - var comparer = getStringComparer(ignoreCase); for (var i = 0; i < sharedLength; i++) { - var result = comparer(aComponents[i], bComponents[i]); + var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); if (result !== 0 /* EqualTo */) { return result; } } return compareValues(aComponents.length, bComponents.length); } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, getStringComparer(ignoreCase)); + } ts.comparePaths = comparePaths; function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } if (parent === undefined || child === undefined) return false; if (parent === child) return true; - parent = removeTrailingDirectorySeparator(parent); - child = removeTrailingDirectorySeparator(child); - if (parent === child) - return true; - var parentComponents = getNormalizedPathComponents(parent, currentDirectory); - var childComponents = getNormalizedPathComponents(child, currentDirectory); + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); if (childComponents.length < parentComponents.length) { return false; } - var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; + var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer; if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } @@ -3932,19 +4147,19 @@ var ts; function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name_1 = combinePaths(path, current); + var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsOneOf(name_1, extensions)) + if (extensions && !fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) return "continue"; if (!includeFileRegexes) { - results[0].push(name_1); + results[0].push(name); } else { var includeIndex = findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); if (includeIndex !== -1) { - results[includeIndex].push(name_1); + results[includeIndex].push(name); } } }; @@ -3960,11 +4175,11 @@ var ts; } for (var _c = 0, _d = sort(directories, compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name_2 = combinePaths(path, current); + var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name_2, absoluteName, depth); + visitDirectory(name, absoluteName, depth); } } } @@ -4050,13 +4265,17 @@ var ts; ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { - var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { - return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; + function isJavaScriptLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } function hasJavaScriptFileExtension(fileName) { return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } @@ -4128,7 +4347,7 @@ var ts; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */]; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { var ext = extensionsToRemove_1[_i]; @@ -4149,9 +4368,14 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return (removeFileExtension(path) + newExtension); + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -4437,6 +4661,10 @@ var ts; return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } ts.extensionIsTypeScript = extensionIsTypeScript; + function resolutionExtensionIsTypeScriptOrJson(ext) { + return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -4457,14 +4685,34 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - function getAnyExtensionFromPath(path) { + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive); + } var baseFileName = getBaseFileName(path); var extensionIndex = baseFileName.lastIndexOf("."); if (extensionIndex >= 0) { return baseFileName.substring(extensionIndex); } + return ""; } ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -4566,12 +4814,12 @@ var ts; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { + var _a; return _a = {}, _a[PollingInterval.Low] = levels.Low, _a[PollingInterval.Medium] = levels.Medium, _a[PollingInterval.High] = levels.High, _a; - var _a; } var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); @@ -4936,6 +5184,7 @@ var ts; readDirectory: readDirectory, getModifiedTime: getModifiedTime, createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, getMemoryUsage: function () { if (global.gc) { global.gc(); @@ -5300,10 +5549,10 @@ var ts; if (entry === "." || entry === "..") { continue; } - var name_3 = ts.combinePaths(path, entry); + var name = ts.combinePaths(path, entry); var stat = void 0; try { - stat = _fs.statSync(name_3); + stat = _fs.statSync(name); } catch (e) { continue; @@ -5374,6 +5623,11 @@ var ts; hash.update(data); return hash.digest("hex"); } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -5685,7 +5939,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -6162,6 +6416,7 @@ var ts; Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -6345,6 +6600,17 @@ var ts; Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -6443,6 +6709,7 @@ var ts; Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -6506,6 +6773,12 @@ var ts; Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), }; })(ts || (ts = {})); var ts; @@ -8256,11 +8529,10 @@ var ts; } } function scanJSDocToken() { + startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; } - startPos = pos; - tokenPos = pos; var ch = text.charCodeAt(pos); pos++; switch (ch) { @@ -8666,7 +8938,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 294 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 298 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8868,12 +9140,12 @@ var ts; case 159 /* IndexSignature */: case 162 /* FunctionType */: case 163 /* ConstructorType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: case 235 /* InterfaceDeclaration */: case 236 /* TypeAliasDeclaration */: - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: case 233 /* FunctionDeclaration */: case 153 /* MethodDeclaration */: case 154 /* Constructor */: @@ -8881,6 +9153,9 @@ var ts; case 156 /* SetAccessor */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + case 287 /* JSDocSignature */: return true; default: ts.assertTypeIsNever(node); @@ -8903,6 +9178,12 @@ var ts; case 243 /* ImportDeclaration */: case 242 /* ImportEqualsDeclaration */: case 213 /* VariableStatement */: + case 234 /* ClassDeclaration */: + case 233 /* FunctionDeclaration */: + case 238 /* ModuleDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 237 /* EnumDeclaration */: return true; default: return false; @@ -8916,13 +9197,7 @@ var ts; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { - var current = node.parent; - while (current) { - if (isBlockScope(current, current.parent)) { - return current; - } - current = current.parent; - } + return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; // Return display name of an identifier @@ -9040,6 +9315,8 @@ var ts; case 155 /* GetAccessor */: case 156 /* SetAccessor */: case 236 /* TypeAliasDeclaration */: + case 151 /* PropertyDeclaration */: + case 150 /* PropertySignature */: errorNode = node.name; break; case 192 /* ArrowFunction */: @@ -9070,6 +9347,10 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; + } + ts.isJsonSourceFile = isJsonSourceFile; function isConstEnumDeclaration(node) { return node.kind === 237 /* EnumDeclaration */ && isConst(node); } @@ -9161,12 +9442,12 @@ var ts; case 145 /* QualifiedName */: case 184 /* PropertyAccessExpression */: case 99 /* ThisKeyword */: - var parent_1 = node.parent; - if (parent_1.kind === 164 /* TypeQuery */) { + var parent = node.parent; + if (parent.kind === 164 /* TypeQuery */) { return false; } - if (parent_1.kind === 178 /* ImportType */) { - return !parent_1.isTypeOf; + if (parent.kind === 178 /* ImportType */) { + return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: // @@ -9174,19 +9455,19 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (160 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 178 /* LastTypeNode */) { + if (160 /* FirstTypeNode */ <= parent.kind && parent.kind <= 178 /* LastTypeNode */) { return true; } - switch (parent_1.kind) { + switch (parent.kind) { case 206 /* ExpressionWithTypeArguments */: - return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case 147 /* TypeParameter */: - return node === parent_1.constraint; + return node === parent.constraint; case 151 /* PropertyDeclaration */: case 150 /* PropertySignature */: case 148 /* Parameter */: case 231 /* VariableDeclaration */: - return node === parent_1.type; + return node === parent.type; case 233 /* FunctionDeclaration */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: @@ -9195,16 +9476,16 @@ var ts; case 152 /* MethodSignature */: case 155 /* GetAccessor */: case 156 /* SetAccessor */: - return node === parent_1.type; + return node === parent.type; case 157 /* CallSignature */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: - return node === parent_1.type; + return node === parent.type; case 189 /* TypeAssertionExpression */: - return node === parent_1.type; + return node === parent.type; case 186 /* CallExpression */: case 187 /* NewExpression */: - return ts.contains(parent_1.typeArguments, node); + return ts.contains(parent.typeArguments, node); case 188 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; @@ -9409,6 +9690,23 @@ var ts; }); } ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.isObjectLiteralExpression(expression) && expression; + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral && + ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -9543,13 +9841,13 @@ var ts; function getImmediatelyInvokedFunctionExpression(func) { if (func.kind === 191 /* FunctionExpression */ || func.kind === 192 /* ArrowFunction */) { var prev = func; - var parent_2 = func.parent; - while (parent_2.kind === 190 /* ParenthesizedExpression */) { - prev = parent_2; - parent_2 = parent_2.parent; + var parent = func.parent; + while (parent.kind === 190 /* ParenthesizedExpression */) { + prev = parent; + parent = parent.parent; } - if (parent_2.kind === 186 /* CallExpression */ && parent_2.expression === prev) { - return parent_2; + if (parent.kind === 186 /* CallExpression */ && parent.expression === prev) { + return parent; } } } @@ -9786,6 +10084,10 @@ var ts; return node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJsonFile(node) { + return node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { return node && !!(node.flags & 2097152 /* JSDoc */); } @@ -9899,9 +10201,9 @@ var ts; /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ function getOuterNameOfJsInitializer(node) { if (ts.isBinaryExpression(node.parent)) { - var parent_3 = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; - if (parent_3.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent_3.left)) { - return parent_3.left; + var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { + return parent.left; } } else if (ts.isVariableDeclaration(node.parent)) { @@ -10010,6 +10312,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243 /* ImportDeclaration */: case 249 /* ExportDeclaration */: @@ -10019,12 +10325,13 @@ var ts; case 186 /* CallExpression */: return node.parent; case 177 /* LiteralType */: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243 /* ImportDeclaration */: @@ -10073,12 +10380,20 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 281 /* JSDocFunctionType */ && + return node.kind === 283 /* JSDocFunctionType */ && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 296 /* JSDocTypedefTag */ || node.kind === 291 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && @@ -10100,6 +10415,8 @@ var ts; return v && v.initializer; case 151 /* PropertyDeclaration */: return node.initializer; + case 269 /* PropertyAssignment */: + return node.initializer; } } function getSingleVariableOfVariableStatement(node) { @@ -10113,9 +10430,9 @@ var ts; node.body.kind === 238 /* ModuleDeclaration */ && node.body; } - function getJSDocCommentsAndTags(node) { + function getJSDocCommentsAndTags(hostNode) { var result; - getJSDocCommentsAndTagsWorker(node); + getJSDocCommentsAndTagsWorker(hostNode); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; @@ -10130,8 +10447,7 @@ var ts; // * @returns {number} // */ // var x = function(name) { return name.length; } - if (parent.parent && - (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { + if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) { getJSDocCommentsAndTagsWorker(parent.parent); } if (parent.parent && parent.parent.parent && @@ -10140,8 +10456,8 @@ var ts; getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } - if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || - ts.isBinaryExpression(parent) && getSpecialPropertyAssignmentKind(parent) !== 0 /* None */ || + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */ || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */ || node.kind === 184 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 215 /* ExpressionStatement */) { getJSDocCommentsAndTagsWorker(parent); } @@ -10149,7 +10465,7 @@ var ts; if (node.kind === 148 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -10176,7 +10492,10 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - var host = getJSDocHost(node); + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || @@ -10185,19 +10504,9 @@ var ts; host; return decl && ts.isFunctionLike(decl) ? decl : undefined; } - ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; function getJSDocHost(node) { - while (node.parent.kind === 284 /* JSDocTypeLiteral */) { - if (node.parent.parent.kind === 292 /* JSDocTypedefTag */) { - node = node.parent.parent; - } - else { - // node.parent.parent is a type expression, child of a parameter type - node = node.parent.parent.parent; - } - } - ts.Debug.assert(node.parent.kind === 283 /* JSDocComment */); - return node.parent.parent; + return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent; } ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { @@ -10212,7 +10521,8 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282 /* JSDocVariadicType */; + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || type && type.kind === 284 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -10354,8 +10664,14 @@ var ts; if (ts.isDeclaration(name.parent)) { return name.parent.name === name; } - var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + else if (ts.isQualifiedName(name.parent)) { + var tag = name.parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + } + else { + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + } default: return false; } @@ -10735,7 +11051,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: return 0; case 203 /* SpreadElement */: return 1; @@ -11064,8 +11380,8 @@ var ts; }; } ts.createTextWriter = createTextWriter; - function getResolvedExternalModuleName(host, file) { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { @@ -11079,12 +11395,13 @@ var ts; /** * Resolves a local path to a path which is absolute to the base of the emit */ - function getExternalModuleNameFromPath(host, fileName) { + function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.removeFileExtension(relativePath); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { @@ -11178,7 +11495,8 @@ var ts; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { - if (signature.parameters.length) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { var thisParameter = signature.parameters[0]; if (parameterIsThisKeyword(thisParameter)) { return thisParameter; @@ -11263,6 +11581,9 @@ var ts; * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { + if (ts.isJSDocSignature(node)) { + return node.type && node.type.typeExpression && node.type.typeExpression.type; + } return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; @@ -11271,12 +11592,27 @@ var ts; * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ function getEffectiveTypeParameterDeclarations(node) { - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 285 /* JSDocComment */); + var templateTags = ts.flatMap(ts.filter(node.parent.tags, ts.isJSDocTemplateTag), function (tag) { return tag.typeParameters; }); + var templateTagNodes = templateTags; + templateTagNodes.pos = templateTagNodes.length > 0 ? ts.first(templateTagNodes).pos : node.pos; + templateTagNodes.end = templateTagNodes.length > 0 ? ts.last(templateTagNodes).end : node.end; + templateTagNodes.hasTrailingComma = false; + return templateTagNodes; + } + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; + // template tags are only available when a typedef isn't already using them + var tag = ts.find(ts.getJSDocTags(node), function (tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + }); + return (tag && tag.typeParameters) || ts.emptyArray; } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** @@ -11813,10 +12149,10 @@ var ts; } function getEnumMembers(enumObject) { var result = []; - for (var name_4 in enumObject) { - var value = enumObject[name_4]; + for (var name in enumObject) { + var value = enumObject[name]; if (typeof value === "number") { - result.push([value, name_4]); + result.push([value, name]); } } return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); @@ -12664,11 +13000,11 @@ var ts; break; case 71 /* Identifier */: return declaration; - case 293 /* JSDocPropertyTag */: - case 288 /* JSDocParameterTag */: { - var name_5 = declaration.name; - if (name_5.kind === 145 /* QualifiedName */) { - return name_5.right; + case 297 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 145 /* QualifiedName */) { + return name.right; } break; } @@ -12684,7 +13020,9 @@ var ts; return undefined; } } - case 292 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + return declaration.name; + case 296 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); case 248 /* ExportAssignment */: { var expression = declaration.expression; @@ -12726,8 +13064,8 @@ var ts; function getJSDocParameterTags(param) { if (param.name) { if (ts.isIdentifier(param.name)) { - var name_6 = param.name.escapedText; - return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_6; }); + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); } else { var i = param.parent.parameters.indexOf(param); @@ -12817,7 +13155,9 @@ var ts; var tags = node.jsDocCache; // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); } return tags; } @@ -12935,6 +13275,11 @@ var ts; return node.kind === 159 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 156 /* SetAccessor */ || node.kind === 155 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { return node.kind === 160 /* TypePredicate */; @@ -13063,7 +13408,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296 /* PartiallyEmittedExpression */) { + while (node.kind === 300 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -13419,81 +13764,89 @@ var ts; ts.isBundle = isBundle; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 275 /* JSDocTypeExpression */; + return node.kind === 277 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 276 /* JSDocAllType */; + return node.kind === 278 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 277 /* JSDocUnknownType */; + return node.kind === 279 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 278 /* JSDocNullableType */; + return node.kind === 280 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 279 /* JSDocNonNullableType */; + return node.kind === 281 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 280 /* JSDocOptionalType */; + return node.kind === 282 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 281 /* JSDocFunctionType */; + return node.kind === 283 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 282 /* JSDocVariadicType */; + return node.kind === 284 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 283 /* JSDocComment */; + return node.kind === 285 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 286 /* JSDocAugmentsTag */; + return node.kind === 289 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 287 /* JSDocClassTag */; + return node.kind === 290 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { - return node.kind === 288 /* JSDocParameterTag */; + return node.kind === 292 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 289 /* JSDocReturnTag */; + return node.kind === 293 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 290 /* JSDocTypeTag */; + return node.kind === 294 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 291 /* JSDocTemplateTag */; + return node.kind === 295 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 292 /* JSDocTypedefTag */; + return node.kind === 296 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 293 /* JSDocPropertyTag */; + return node.kind === 297 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 293 /* JSDocPropertyTag */ || node.kind === 288 /* JSDocParameterTag */; + return node.kind === 297 /* JSDocPropertyTag */ || node.kind === 292 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 284 /* JSDocTypeLiteral */; + return node.kind === 286 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 291 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 287 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); // Node tests // @@ -13502,7 +13855,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 294 /* SyntaxList */; + return n.kind === 298 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13647,10 +14000,11 @@ var ts; switch (kind) { case 152 /* MethodSignature */: case 157 /* CallSignature */: + case 287 /* JSDocSignature */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: case 162 /* FunctionType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: case 163 /* ConstructorType */: return true; default: @@ -13734,13 +14088,13 @@ var ts; || kind === 95 /* NullKeyword */ || kind === 131 /* NeverKeyword */ || kind === 206 /* ExpressionWithTypeArguments */ - || kind === 276 /* JSDocAllType */ - || kind === 277 /* JSDocUnknownType */ - || kind === 278 /* JSDocNullableType */ - || kind === 279 /* JSDocNonNullableType */ - || kind === 280 /* JSDocOptionalType */ - || kind === 281 /* JSDocFunctionType */ - || kind === 282 /* JSDocVariadicType */; + || kind === 278 /* JSDocAllType */ + || kind === 279 /* JSDocUnknownType */ + || kind === 280 /* JSDocNullableType */ + || kind === 281 /* JSDocNonNullableType */ + || kind === 282 /* JSDocOptionalType */ + || kind === 283 /* JSDocFunctionType */ + || kind === 284 /* JSDocVariadicType */; } /** * Node test that determines whether a node is a valid type node. @@ -13962,8 +14316,8 @@ var ts; case 203 /* SpreadElement */: case 207 /* AsExpression */: case 205 /* OmittedExpression */: - case 297 /* CommaListExpression */: - case 296 /* PartiallyEmittedExpression */: + case 301 /* CommaListExpression */: + case 300 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13977,12 +14331,12 @@ var ts; ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 296 /* PartiallyEmittedExpression */; + return node.kind === 300 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 295 /* NotEmittedStatement */; + return node.kind === 299 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -14093,7 +14447,9 @@ var ts; || kind === 236 /* TypeAliasDeclaration */ || kind === 147 /* TypeParameter */ || kind === 231 /* VariableDeclaration */ - || kind === 292 /* JSDocTypedefTag */; + || kind === 296 /* JSDocTypedefTag */ + || kind === 291 /* JSDocCallbackTag */ + || kind === 297 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { return kind === 233 /* FunctionDeclaration */ @@ -14128,14 +14484,14 @@ var ts; || kind === 213 /* VariableStatement */ || kind === 218 /* WhileStatement */ || kind === 225 /* WithStatement */ - || kind === 295 /* NotEmittedStatement */ - || kind === 299 /* EndOfDeclarationMarker */ - || kind === 298 /* MergeDeclarationMarker */; + || kind === 299 /* NotEmittedStatement */ + || kind === 303 /* EndOfDeclarationMarker */ + || kind === 302 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 147 /* TypeParameter */) { - return node.parent.kind !== 291 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 295 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -14230,18 +14586,18 @@ var ts; /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 275 /* FirstJSDocNode */ && node.kind <= 293 /* LastJSDocNode */; + return node.kind >= 277 /* FirstJSDocNode */ && node.kind <= 297 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 283 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node); + return node.kind === 285 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 285 /* FirstJSDocTagNode */ && node.kind <= 293 /* LastJSDocTagNode */; + return node.kind >= 288 /* FirstJSDocTagNode */ && node.kind <= 297 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -14292,12 +14648,12 @@ var ts; case 231 /* VariableDeclaration */: case 233 /* FunctionDeclaration */: case 236 /* TypeAliasDeclaration */: - case 275 /* JSDocTypeExpression */: - case 278 /* JSDocNullableType */: - case 279 /* JSDocNonNullableType */: - case 280 /* JSDocOptionalType */: - case 281 /* JSDocFunctionType */: - case 282 /* JSDocVariadicType */: + case 277 /* JSDocTypeExpression */: + case 280 /* JSDocNullableType */: + case 281 /* JSDocNonNullableType */: + case 282 /* JSDocOptionalType */: + case 283 /* JSDocFunctionType */: + case 284 /* JSDocVariadicType */: return true; } return false; @@ -14787,7 +15143,7 @@ var ts; return visitNode(cbNode, node.expression); case 252 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 254 /* JsxElement */: return visitNode(cbNode, node.openingElement) || @@ -14814,23 +15170,23 @@ var ts; visitNode(cbNode, node.expression); case 257 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 275 /* JSDocTypeExpression */: + case 277 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 279 /* JSDocNonNullableType */: + case 281 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 278 /* JSDocNullableType */: + case 280 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 280 /* JSDocOptionalType */: + case 282 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 283 /* JSDocComment */: + case 285 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 288 /* JSDocParameterTag */: - case 293 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: + case 297 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -14839,17 +15195,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 289 /* JSDocReturnTag */: + case 293 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 290 /* JSDocTypeTag */: + case 294 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 286 /* JSDocAugmentsTag */: + case 289 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 292 /* JSDocTypedefTag */: + case 296 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 275 /* JSDocTypeExpression */) { + node.typeExpression.kind === 277 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -14857,7 +15213,16 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 284 /* JSDocTypeLiteral */: + case 291 /* JSDocCallbackTag */: + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 287 /* JSDocSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 286 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -14865,7 +15230,7 @@ var ts; } } return; - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -14873,7 +15238,13 @@ var ts; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; @@ -15033,6 +15404,13 @@ var ts; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + return result_1; + } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); @@ -15050,25 +15428,57 @@ var ts; return isInvalid ? entityName : undefined; } Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function parseJsonText(fileName, sourceText) { - initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); // Set source file so that errors will be reported with this file name sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); - var result = sourceFile; // Prime the scanner. nextToken(); + var pos = getNodePos(); if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); sourceFile.endOfFileToken = parseTokenNode(); } - else if (token() === 17 /* OpenBraceToken */ || - lookAhead(function () { return token() === 9 /* StringLiteral */; })) { - result.jsonObject = parseObjectLiteralExpression(); + else { + var statement = createNode(215 /* ExpressionStatement */); + switch (token()) { + case 21 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 38 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); } - else { - parseExpected(17 /* OpenBraceToken */); + if (setParentNodes) { + fixupParentReferences(sourceFile); } sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; clearState(); return result; } @@ -15092,9 +15502,11 @@ var ts; switch (scriptKind) { case 1 /* JS */: case 2 /* JSX */: - case 6 /* JSON */: contextFlags = 65536 /* JavaScriptFile */; break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; default: contextFlags = 0 /* None */; break; @@ -16340,9 +16752,9 @@ var ts; return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(276 /* JSDocAllType */); + var result = createNode(278 /* JSDocAllType */); if (postFixEquals) { - return createJSDocPostfixType(280 /* JSDocOptionalType */, result); + return createJSDocPostfixType(282 /* JSDocOptionalType */, result); } else { nextToken(); @@ -16350,7 +16762,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(279 /* JSDocNonNullableType */); + var result = createNode(281 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -16374,18 +16786,18 @@ var ts; token() === 29 /* GreaterThanToken */ || token() === 58 /* EqualsToken */ || token() === 49 /* BarToken */) { - var result = createNode(277 /* JSDocUnknownType */, pos); + var result = createNode(279 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(278 /* JSDocNullableType */, pos); + var result = createNode(280 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(281 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(283 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); @@ -16407,12 +16819,12 @@ var ts; var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseType(); if (dotdotdot) { - var variadic = createNode(282 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(284 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } if (token() === 58 /* EqualsToken */) { - return createJSDocPostfixType(280 /* JSDocOptionalType */, type); + return createJSDocPostfixType(282 /* JSDocOptionalType */, type); } return type; } @@ -16496,15 +16908,19 @@ var ts; node.initializer = parseInitializer(); return finishNode(node); } + /** + * @returns If return type parsing succeeds + */ function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */)); - } - function parseReturnType(returnToken, isType) { - return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + return signature.type !== undefined; + } + return true; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36 /* EqualsGreaterThanToken */) { @@ -16783,6 +17199,9 @@ var ts; var node = createNode(172 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); + if (!node.type) { + return undefined; + } parseExpected(20 /* CloseParenToken */); return finishNode(node); } @@ -16791,7 +17210,12 @@ var ts; if (kind === 163 /* ConstructorType */) { parseExpected(94 /* NewKeyword */); } - fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + if (!fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */ | (sourceFile.languageVariant === 1 /* JSX */ ? 8 /* RequireCompleteParameterList */ : 0), node)) { + return undefined; + } + if (!node.parameters) { + return undefined; + } return finishNode(node); } function parseKeywordAndNoDot() { @@ -16947,14 +17371,14 @@ var ts; while (!scanner.hasPrecedingLineBreak()) { switch (token()) { case 51 /* ExclamationToken */: - type = createJSDocPostfixType(279 /* JSDocNonNullableType */, type); + type = createJSDocPostfixType(281 /* JSDocNonNullableType */, type); break; case 55 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createJSDocPostfixType(278 /* JSDocNullableType */, type); + type = createJSDocPostfixType(280 /* JSDocNullableType */, type); break; case 21 /* OpenBracketToken */: parseExpected(21 /* OpenBracketToken */); @@ -17518,7 +17942,7 @@ var ts; // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] if (token() === 120 /* AsyncKeyword */) { nextToken(); - // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { return 0 /* False */; @@ -17542,7 +17966,9 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node); + if (!fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node)) { + return undefined; + } // If we couldn't get parameters, we definitely could not parse out an arrow function. if (!node.parameters) { return undefined; @@ -19905,7 +20331,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos()); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -19925,6 +20351,7 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var _a; var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -19942,7 +20369,6 @@ var ts; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; - var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; var JSDocState; @@ -19953,8 +20379,9 @@ var ts; })(JSDocState || (JSDocState = {})); var PropertyLikeParse; (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; @@ -20002,7 +20429,7 @@ var ts; case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); - parseTag(indent); + addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning // for malformed examples like `/** @param {string} x @returns {number} the length */` @@ -20076,12 +20503,29 @@ var ts; } } function createJSDocComment() { - var result = createNode(283 /* JSDocComment */, start); + var result = createNode(285 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { nextJSDocToken(); } @@ -20110,8 +20554,7 @@ var ts; case "arg": case "argument": case "param": - addTag(parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */, indent)); - return; + return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); case "return": case "returns": tag = parseReturnTag(atToken, tagName); @@ -20123,7 +20566,10 @@ var ts; tag = parseTypeTag(atToken, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(atToken, tagName, indent); break; default: tag = parseUnknownTag(atToken, tagName); @@ -20137,8 +20583,11 @@ var ts; // a badly malformed tag should not be added to the list of tags return; } - tag.comment = parseTagComments(indent + tag.end - tag.pos); - addTag(tag); + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; } function parseTagComments(indent) { var comments = []; @@ -20201,12 +20650,15 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { - var result = createNode(285 /* JSDocTag */, atToken.pos); + var result = createNode(288 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } function addTag(tag) { + if (!tag) { + return; + } if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -20257,9 +20709,9 @@ var ts; if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var result = target === 1 /* Parameter */ ? - createNode(288 /* JSDocParameterTag */, atToken.pos) : - createNode(293 /* JSDocPropertyTag */, atToken.pos); + var result = target === 1 /* Property */ ? + createNode(297 /* JSDocPropertyTag */, atToken.pos) : + createNode(292 /* JSDocParameterTag */, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -20279,18 +20731,18 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name, target) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 288 /* JSDocParameterTag */ || child.kind === 293 /* JSDocPropertyTag */) { + if (child.kind === 292 /* JSDocParameterTag */ || child.kind === 297 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; if (typeExpression.type.kind === 166 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; @@ -20301,27 +20753,27 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 293 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(289 /* JSDocReturnTag */, atToken.pos); + var result = createNode(293 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 290 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 294 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(290 /* JSDocTypeTag */, atToken.pos); + var result = createNode(294 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var result = createNode(286 /* JSDocAugmentsTag */, atToken.pos); + var result = createNode(289 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); @@ -20349,32 +20801,23 @@ var ts; return node; } function parseClassTag(atToken, tagName) { - var tag = createNode(287 /* JSDocClassTag */, atToken.pos); + var tag = createNode(290 /* JSDocClassTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); } - function parseTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(292 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(296 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { - // if node is identifier - use it as name - // otherwise use name of the rightmost part that we were able to parse - typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); skipWhitespace(); + typedefTag.comment = parseTagComments(indent); typedefTag.typeExpression = typeExpression; + var end; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; @@ -20382,9 +20825,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 290 /* JSDocTypeTag */) { + if (child.kind === 294 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -20403,23 +20846,68 @@ var ts; typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; } } - return finishNode(typedefTag); - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); - return finishNode(jsDocNamespaceNode); + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { + var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } - if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { - typeNameOrNamespaceName.isInJSDocNamespace = true; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(atToken, tagName, indent) { + var callbackTag = createNode(291 /* JSDocCallbackTag */, atToken.pos); + callbackTag.atToken = atToken; + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var start = scanner.getStartPos(); + var jsdocSignature = createNode(287 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (token() === 57 /* AtToken */) { + nextJSDocToken(); + var tag = parseTag(indent); + if (tag && tag.kind === 293 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; } - return typeNameOrNamespaceName; } } function escapedTextsEqual(a, b) { @@ -20435,7 +20923,7 @@ var ts; return a.escapedText === b.escapedText; } function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(0 /* Property */); + return parseChildParameterOrPropertyTag(1 /* Property */); } function parseChildParameterOrPropertyTag(target, name) { var canParseTag = true; @@ -20445,7 +20933,8 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 288 /* JSDocParameterTag */ && + if (child && child.kind === 292 /* JSDocParameterTag */ && + target !== 4 /* CallbackParameter */ && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -20484,20 +20973,20 @@ var ts; var t; switch (tagName.escapedText) { case "type": - return target === 0 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - t = 0 /* Property */; + t = 1 /* Property */; break; case "arg": case "argument": case "param": - t = 1 /* Parameter */; + t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; default: return false; } - if (target !== t) { + if (!(target & t)) { return false; } var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); @@ -20513,13 +21002,13 @@ var ts; var typeParametersPos = getNodePos(); while (true) { var typeParameter = createNode(147 /* TypeParameter */); - var name_7 = parseJSDocIdentifierNameWithOptionalBraces(); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); - if (!name_7) { + if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - typeParameter.name = name_7; + typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); if (token() === 26 /* CommaToken */) { @@ -20530,7 +21019,7 @@ var ts; break; } } - var result = createNode(291 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(295 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -20557,11 +21046,11 @@ var ts; // but it's not worth it to enforce that restriction. } while (parseOptional(23 /* DotToken */)) { - var name_8 = parseJSDocIdentifierName(/*createIfMissing*/ true); + var name = parseJSDocIdentifierName(/*createIfMissing*/ true); if (parseOptional(21 /* OpenBracketToken */)) { parseExpected(22 /* CloseBracketToken */); } - entity = createQualifiedName(entity, name_8); + entity = createQualifiedName(entity, name); } return entity; } @@ -20579,7 +21068,7 @@ var ts; var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); var result = createNode(71 /* Identifier */, pos); - result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); return result; @@ -21193,8 +21682,8 @@ var ts; function extractPragmas(pragmas, range, text) { var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { - var name_9 = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks - var pragma = ts.commentPragmas[name_9]; + var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks + var pragma = ts.commentPragmas[name]; if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { return; } @@ -21221,10 +21710,10 @@ var ts; } } } - pragmas.push({ name: name_9, args: { arguments: argument, range: range } }); + pragmas.push({ name: name, args: { arguments: argument, range: range } }); } else { - pragmas.push({ name: name_9, args: { arguments: {}, range: range } }); + pragmas.push({ name: name, args: { arguments: {}, range: range } }); } return; } @@ -21383,7 +21872,7 @@ var ts; var thisParentContainer; // Container one level up var blockScopeContainer; var lastContainer; - var delayedTypedefs; + var delayedTypeAliases; var seenThisKeyword; // state used by control flow analysis var currentFlow; @@ -21441,7 +21930,7 @@ var ts; thisParentContainer = undefined; blockScopeContainer = undefined; lastContainer = undefined; - delayedTypedefs = undefined; + delayedTypeAliases = undefined; seenThisKeyword = false; currentFlow = undefined; currentBreakTarget = undefined; @@ -21515,6 +22004,7 @@ var ts; return "__constructor" /* Constructor */; case 162 /* FunctionType */: case 157 /* CallSignature */: + case 287 /* JSDocSignature */: return "__call" /* Call */; case 163 /* ConstructorType */: case 158 /* ConstructSignature */: @@ -21523,6 +22013,10 @@ var ts; return "__index" /* Index */; case 249 /* ExportDeclaration */: return "__export" /* ExportStar */; + case 273 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; case 199 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { // module.exports = ... @@ -21530,18 +22024,15 @@ var ts; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); case 148 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 281 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 283 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; - case 292 /* JSDocTypedefTag */: - var name_10 = ts.getNameOfJSDocTypedef(node); - return typeof name_10 !== "undefined" ? name_10.escapedText : undefined; } } function getDisplayName(node) { @@ -21679,9 +22170,9 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (node.kind === 292 /* JSDocTypedefTag */) + if (ts.isJSDocTypeAlias(node)) ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypedefTag(node)) { + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } @@ -21846,23 +22337,6 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - // Binding of JsDocComment should be done before the current block scope container changes. - // because the scope of JsDocComment should not be affected by whether the current node is a - // container or not. - if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var j = _a[_i]; - bind(j); - } - } - else { - for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { - var j = _c[_b]; - setParentPointers(node, j); - } - } - } if (checkUnreachable(node)) { bindEachChild(node); return; @@ -21928,11 +22402,9 @@ var ts; case 186 /* CallExpression */: bindCallExpressionFlow(node); break; - case 283 /* JSDocComment */: - bindJSDocComment(node); - break; - case 292 /* JSDocTypedefTag */: - bindJSDocTypedefTag(node); + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 273 /* SourceFile */: @@ -21947,6 +22419,7 @@ var ts; bindEachChild(node); break; } + bindJSDoc(node); } function isNarrowingExpression(expr) { switch (expr.kind) { @@ -22548,23 +23021,10 @@ var ts; bindInitializedVariableFlow(node); } } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 292 /* JSDocTypedefTag */) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - // if the node has a fullName "A.B.C", that means symbol "C" was already bound - // when we visit "fullName"; so when we visit the name "C" as the next child of - // the jsDocTypedefTag, we should skip binding it. - if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { - return; - } - bind(n); - }); + function bindJSDocTypeAlias(node) { + if (node.fullName) { + setParentPointers(node, node.fullName); + } } function bindCallExpressionFlow(node) { // If the target of the call expression is a function expression or arrow function we have @@ -22596,7 +23056,7 @@ var ts; case 237 /* EnumDeclaration */: case 183 /* ObjectLiteralExpression */: case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: + case 286 /* JSDocTypeLiteral */: case 262 /* JsxAttributes */: return 1 /* IsContainer */; case 235 /* InterfaceDeclaration */: @@ -22618,7 +23078,8 @@ var ts; case 155 /* GetAccessor */: case 156 /* SetAccessor */: case 157 /* CallSignature */: - case 281 /* JSDocFunctionType */: + case 287 /* JSDocSignature */: + case 283 /* JSDocFunctionType */: case 162 /* FunctionType */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: @@ -22680,7 +23141,7 @@ var ts; case 237 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: + case 286 /* JSDocTypeLiteral */: case 183 /* ObjectLiteralExpression */: case 235 /* InterfaceDeclaration */: case 262 /* JsxAttributes */: @@ -22694,6 +23155,7 @@ var ts; case 163 /* ConstructorType */: case 157 /* CallSignature */: case 158 /* ConstructSignature */: + case 287 /* JSDocSignature */: case 159 /* IndexSignature */: case 153 /* MethodDeclaration */: case 152 /* MethodSignature */: @@ -22703,7 +23165,9 @@ var ts; case 233 /* FunctionDeclaration */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: case 236 /* TypeAliasDeclaration */: case 176 /* MappedType */: // All the children of these container types are never visible through another @@ -22878,22 +23342,35 @@ var ts; bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); } function delayedBindJSDocTypedefTag() { - if (!delayedTypedefs) { + if (!delayedTypeAliases) { return; } var saveContainer = container; var saveLastContainer = lastContainer; var saveBlockScopeContainer = blockScopeContainer; var saveParent = parent; - for (var _i = 0, delayedTypedefs_1 = delayedTypedefs; _i < delayedTypedefs_1.length; _i++) { - var delay = delayedTypedefs_1[_i]; - (container = delay.container, lastContainer = delay.lastContainer, blockScopeContainer = delay.blockScopeContainer, parent = delay.parent); - bindBlockScopedDeclaration(delay.typedef, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } } container = saveContainer; lastContainer = saveLastContainer; blockScopeContainer = saveBlockScopeContainer; parent = saveParent; + currentFlow = saveCurrentFlow; } // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized // check for reserved words used as identifiers in strict mode code. @@ -23045,8 +23522,6 @@ var ts; // Here the current node is "foo", which is a container, but the scope of "MyType" should // not be inside "foo". Therefore we always bind @typedef before bind the parent node, // and skip binding this tag later when binding all the other jsdoc tags. - if (ts.isInJavaScriptFile(node)) - bindJSDocTypedefTagIfAny(node); // First we bind declaration nodes to a symbol if possible. We'll both create a symbol // and then potentially add the symbol to an appropriate symbol table. Possible // destination symbol tables are: @@ -23077,25 +23552,22 @@ var ts; } else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + bindJSDoc(node); } inStrictMode = saveInStrictMode; } - function bindJSDocTypedefTagIfAny(node) { - if (!ts.hasJSDocNodes(node)) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 292 /* JSDocTypedefTag */) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); } } } @@ -23130,7 +23602,7 @@ var ts; // current "blockScopeContainer" needs to be set to its immediate namespace parent. if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 292 /* JSDocTypedefTag */) { + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); @@ -23232,11 +23704,12 @@ var ts; case 156 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); case 162 /* FunctionType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: + case 287 /* JSDocSignature */: case 163 /* ConstructorType */: return bindFunctionOrConstructorType(node); case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: + case 286 /* JSDocTypeLiteral */: case 176 /* MappedType */: return bindAnonymousTypeWorker(node); case 183 /* ObjectLiteralExpression */: @@ -23292,24 +23765,23 @@ var ts; // falls through case 239 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 288 /* JSDocParameterTag */: - if (node.parent.kind !== 284 /* JSDocTypeLiteral */) { + case 292 /* JSDocParameterTag */: + if (node.parent.kind === 287 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 286 /* JSDocTypeLiteral */) { break; } // falls through - case 293 /* JSDocPropertyTag */: + case 297 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 280 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 282 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 292 /* JSDocTypedefTag */: { - var fullName = node.fullName; - if (!fullName || fullName.kind === 71 /* Identifier */) { - (delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node, container: container, lastContainer: lastContainer, blockScopeContainer: blockScopeContainer, parent: parent }); - } - break; - } + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } function bindPropertyWorker(node) { @@ -23323,6 +23795,13 @@ var ts; if (ts.isExternalModule(file)) { bindSourceFileAsExternalModule(); } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } } function bindSourceFileAsExternalModule() { bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); @@ -23352,12 +23831,12 @@ var ts; return; } else { - var parent_4 = node.parent; - if (!ts.isExternalModule(parent_4)) { + var parent_1 = node.parent; + if (!ts.isExternalModule(parent_1)) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_4.isDeclarationFile) { + if (!parent_1.isDeclarationFile) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -23662,6 +24141,9 @@ var ts; } } function bindParameter(node) { + if (node.kind === 292 /* JSDocParameterTag */ && container.kind !== 287 /* JSDocSignature */) { + return; + } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) @@ -23720,24 +24202,30 @@ var ts; : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } function getInferTypeContainer(node) { - while (node) { - var parent_5 = node.parent; - if (parent_5 && parent_5.kind === 170 /* ConditionalType */ && parent_5.extendsType === node) { - return parent_5; - } - node = parent_5; - } - return undefined; + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; } function bindTypeParameter(node) { - if (node.parent.kind === 171 /* InferType */) { - var container_1 = getInferTypeContainer(node.parent); + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); if (container_1) { if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 171 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); } @@ -23999,7 +24487,7 @@ var ts; else { // A ClassDeclaration is ES6 syntax. transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is + // A class with a parameter property assignment, property initializer, computed property name, or decorator is // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. @@ -24136,9 +24624,9 @@ var ts; function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; - // If the PropertyDeclaration has an initializer, we need to inform its ancestor + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. - if (node.initializer) { + if (node.initializer || ts.isComputedPropertyName(node.name)) { transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -24362,7 +24850,7 @@ var ts; break; case 189 /* TypeAssertionExpression */: case 207 /* AsExpression */: - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; @@ -24634,7 +25122,7 @@ var ts; return 940049729 /* BindingPatternExcludes */; case 189 /* TypeAssertionExpression */: case 207 /* AsExpression */: - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: case 190 /* ParenthesizedExpression */: case 97 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; @@ -24652,7 +25140,7 @@ var ts; */ function setParentPointers(parent, child) { child.parent = parent; - ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); } })(ts || (ts = {})); /** @internal */ @@ -24850,7 +25338,8 @@ var ts; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { @@ -24894,7 +25383,13 @@ var ts; function readJson(path, host) { try { var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; } catch (e) { // gracefully handle if readFile fails or returns not JSON @@ -25128,12 +25623,12 @@ var ts; var commonPrefix = getCommonPrefix(path, resolvedFileName); var current = path; while (true) { - var parent_6 = ts.getDirectoryPath(current); - if (parent_6 === current || directoryPathMap.has(parent_6)) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { break; } - directoryPathMap.set(parent_6, result); - current = parent_6; + directoryPathMap.set(parent, result); + current = parent; if (current === commonPrefix) { break; } @@ -25425,7 +25920,11 @@ var ts; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + var result = jsOnly ? + tryResolve(Extensions.JavaScript) : + (tryResolve(Extensions.TypeScript) || + tryResolve(Extensions.JavaScript) || + (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); @@ -25480,7 +25979,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); if (!directoryProbablyExists(parentOfCandidate, state.host)) { @@ -25565,6 +26064,10 @@ var ts; * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (extensions === Extensions.Json) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -25585,9 +26088,9 @@ var ts; function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + var directory_1 = ts.getDirectoryPath(candidate); + if (directory_1) { + onlyRecordFailures = !directoryProbablyExists(directory_1, state.host); } } switch (extensions) { @@ -25597,6 +26100,8 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.Json: + return tryExtension(".json" /* Json */); } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); @@ -25649,8 +26154,11 @@ var ts; } else { var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string") { - subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */; + if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { + var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; } else { subModuleName = "index.d.ts"; @@ -25683,9 +26191,18 @@ var ts; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); if (!file) { - return undefined; + if (extensions === Extensions.TypeScript) { + // When resolving typescript modules, try resolving using main field as well + file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + if (!file) { + return undefined; + } + } + else { + return undefined; + } } var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); @@ -25718,6 +26235,8 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.Json: + return extension === ".json" /* Json */; case Extensions.TypeScript: return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; case Extensions.DtsOnly: @@ -25788,7 +26307,7 @@ var ts; if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript) { + if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { @@ -26213,7 +26732,7 @@ var ts; checkSourceFile(file); var diagnostics = []; ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); - checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { if (!unusedIsError(kind)) { diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } @@ -26283,6 +26802,7 @@ var ts; var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); @@ -26327,8 +26847,6 @@ var ts; var deferredGlobalExtractSymbol; var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name - var potentiallyUnusedIdentifiers; // Potentially unused identifiers in the source file currently being checked. - var seenPotentiallyUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -26639,17 +27157,17 @@ var ts; } function getJsxNamespace(location) { if (location) { - var file = ts.getSourceFileOfNode(location); - if (file) { - if (file.localJsxNamespace) { - return file.localJsxNamespace; + var file_1 = ts.getSourceFileOfNode(location); + if (file_1) { + if (file_1.localJsxNamespace) { + return file_1.localJsxNamespace; } - var jsxPragma = file.pragmas.get("jsx"); + var jsxPragma = file_1.pragmas.get("jsx"); if (jsxPragma) { var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; - file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); - if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file_1.localJsxFactory) { + return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText; } } } @@ -26761,6 +27279,8 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* JSContainer */) { + var targetValueDeclaration = target.valueDeclaration; + ts.Debug.assert(!!(target.flags & 33554432 /* Transient */)); // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums @@ -26786,7 +27306,12 @@ var ts; } if ((source.flags | target.flags) & 67108864 /* JSContainer */) { var sourceInitializer = ts.getJSInitializerSymbol(source); - var targetInitializer = ts.getJSInitializerSymbol(target); + var init = ts.getDeclaredJavascriptInitializer(targetValueDeclaration) || ts.getAssignedJavascriptInitializer(targetValueDeclaration); + var targetInitializer = init && init.symbol ? init.symbol : target; + if (!(targetInitializer.flags & 33554432 /* Transient */)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } if (sourceInitializer !== source || targetInitializer !== target) { mergeSymbol(targetInitializer, sourceInitializer); } @@ -27070,7 +27595,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 283 /* JSDocComment */) { + if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 285 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -27269,6 +27794,12 @@ var ts; location = location.parent; } break; + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + lastLocation = location; + location = ts.getJSDocHost(location).parent; + continue; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -27384,9 +27915,11 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var parent_7 = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (decl.kind === 147 /* TypeParameter */ && parent_7 === container) { - return true; + if (decl.kind === 147 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + } } } return false; @@ -27453,14 +27986,14 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); if (meaning === namespaceMeaning) { var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); - var parent_8 = errorLocation.parent; + var parent = errorLocation.parent; if (symbol) { - if (ts.isQualifiedName(parent_8)) { - ts.Debug.assert(parent_8.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); - var propName = parent_8.right.escapedText; + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); if (propType) { - error(parent_8, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); return true; } } @@ -27597,8 +28130,8 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); - var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + var file_2 = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file_2, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -27666,24 +28199,24 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { - var name_11 = specifier.propertyName || specifier.name; - if (name_11.escapedText) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; // First check if module was specified with "export=". If so, get the member from the resolved type if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.escapedText); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.escapedText); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); } // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - var symbolFromModule = getExportOfModule(targetSymbol, name_11.escapedText, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name_11.escapedText === "default" /* Default */) { + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? @@ -27691,13 +28224,13 @@ var ts; symbolFromModule || symbolFromVariable; if (!symbol) { var moduleName = getFullyQualifiedName(moduleSymbol); - var declarationName = ts.declarationNameToString(name_11); - var suggestion = getSuggestionForNonexistentModule(name_11, targetSymbol); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { - error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); } else { - error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } } return symbol; @@ -27850,7 +28383,7 @@ var ts; var symbol; if (name.kind === 71 /* Identifier */) { var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSPrototype(name, meaning) : undefined; + var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -27859,40 +28392,40 @@ var ts; else if (name.kind === 145 /* QualifiedName */ || name.kind === 184 /* PropertyAccessExpression */) { var left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); - if (!namespace || ts.nodeIsMissing(right)) { + var namespace_1 = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace_1 || ts.nodeIsMissing(right)) { return undefined; } - else if (namespace === unknownSymbol) { - return namespace; + else if (namespace_1 === unknownSymbol) { + return namespace_1; } if (ts.isInJavaScriptFile(name)) { - var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); + var initializer = ts.getDeclaredJavascriptInitializer(namespace_1.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace_1.valueDeclaration); if (initializer) { - namespace = getSymbolOfNode(initializer); + namespace_1 = getSymbolOfNode(initializer); } // Currently, IIFEs may not have a symbol and we don't know about their contents. Give up in this case. - if (!namespace) { + if (!namespace_1) { return undefined; } - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + if (namespace_1.valueDeclaration && + ts.isVariableDeclaration(namespace_1.valueDeclaration) && + namespace_1.valueDeclaration.initializer && + isCommonJsRequire(namespace_1.valueDeclaration.initializer)) { + var moduleName = namespace_1.valueDeclaration.initializer.arguments[0]; var moduleSym = resolveExternalModuleName(moduleName, moduleName); if (moduleSym) { var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; + namespace_1 = resolvedModuleSymbol; } } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getSymbol(getExportsOfSymbol(namespace_1), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace_1), ts.declarationNameToString(right)); } return undefined; } @@ -27904,24 +28437,37 @@ var ts; return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } /** - * For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSPrototype(name, meaning) { - if (isJSDocTypeReference(name.parent) && ts.isJSDocTag(name.parent.parent.parent)) { - var host_1 = ts.getJSDocHost(name.parent.parent.parent); - if (ts.isExpressionStatement(host_1) && - ts.isBinaryExpression(host_1.expression) && - ts.getSpecialPropertyAssignmentKind(host_1.expression) === 3 /* PrototypeProperty */) { - var symbol = getSymbolOfNode(host_1.expression.left); - if (symbol) { - var secondaryLocation = symbol.parent.valueDeclaration; - return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); - } + function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } + function getJSSpecialAssignmentLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + var symbol = getSymbolOfNode(host.expression.left); + return symbol && symbol.parent.valueDeclaration; + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -27970,7 +28516,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -27982,7 +28528,22 @@ var ts; return undefined; } if (moduleNotFoundError) { - // report errors only if it was requested + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } if (resolutionDiagnostic) { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } @@ -28279,21 +28840,21 @@ var ts; } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - for (var location_1 = enclosingDeclaration; location_1; location_1 = location_1.parent) { + for (var location = enclosingDeclaration; location; location = location.parent) { // Locals of a source file are not in scope (because they get merged into the global symbol table) - if (location_1.locals && !isGlobalSourceFile(location_1)) { - if (result = callback(location_1.locals)) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { return result; } } - switch (location_1.kind) { + switch (location.kind) { case 273 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location_1)) { + if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through case 238 /* ModuleDeclaration */: - if (result = callback(getSymbolOfNode(location_1).exports)) { + if (result = callback(getSymbolOfNode(location).exports)) { return result; } break; @@ -28429,7 +28990,7 @@ var ts; * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { + if (symbol && enclosingDeclaration) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { @@ -28446,6 +29007,14 @@ var ts; } return hasAccessibleDeclarations; } + else { + if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. // It could be a qualified symbol and hence verify the path // e.g.: @@ -28511,6 +29080,11 @@ var ts; isDeclarationVisible(declaration.parent.parent.parent)) { return addVisibleAlias(declaration, declaration.parent.parent); } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } // Declaration is not visible return false; } @@ -28678,7 +29252,7 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined, + visitedSymbols: undefined, inferTypeParameters: undefined }; } @@ -28711,8 +29285,8 @@ var ts; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 272 /* EnumLike */) { - var name_12 = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(name_12, /*typeArguments*/ undefined); + var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (type.flags & (32 /* StringLiteral */)) { return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); @@ -28770,16 +29344,25 @@ var ts; } if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { - return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } - var name_13 = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 32768 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + } + var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return ts.createTypeReferenceNode(name_13, /*typeArguments*/ undefined); + return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { - var name_14 = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name_14, typeArgumentNodes); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); } if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) { var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types; @@ -28828,14 +29411,26 @@ var ts; ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; + var id; if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); if (isJavaScriptConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; @@ -28847,7 +29442,7 @@ var ts; shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, 67216319 /* Value */); } - else if (ts.contains(context.symbolStack, symbol)) { + else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { @@ -28861,19 +29456,13 @@ var ts; else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.symbolStack) { - context.symbolStack = []; - } - var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - return createTypeNodeFromObjectType(type); - } - else { - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + if (!context.visitedSymbols) { + context.visitedSymbols = ts.createMap(); } + context.visitedSymbols.set(id, true); + var result = createTypeNodeFromObjectType(type); + context.visitedSymbols.delete(id); + return result; } } else { @@ -28890,7 +29479,7 @@ var ts; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed } } @@ -28922,11 +29511,6 @@ var ts; var typeLiteralNode = ts.createTypeLiteralNode(members); return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } - function symbolToTypeReferenceName(symbol) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); - return entityName; - } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { @@ -28959,69 +29543,79 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = void 0; + var resultType = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); - var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); - var namePart = symbolToTypeReferenceName(parent_9); - (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); - } - else { - qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); - } + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } } } - var entityName = void 0; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } var typeArgumentNodes = void 0; if (typeArguments.length > 0) { var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } - if (typeArgumentNodes) { - var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; - lastIdentifier.typeArguments = undefined; - } - return ts.createTypeReferenceNode(entityName, typeArgumentNodes); + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } } - function addToQualifiedNameMissingRightIdentifier(left, right) { - ts.Debug.assert(left.right === undefined); - if (right.kind === 71 /* Identifier */) { - left.right = right; - return left; + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; } - var rightPart = right; - while (rightPart.left.kind !== 71 /* Identifier */) { - rightPart = rightPart.left; + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; } - left.right = rightPart.left; - rightPart.left = left; - return right; + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; @@ -29062,9 +29656,9 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name_15 = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); - if (name_15 && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name_15, saveEnclosingDeclaration, 67216319 /* Value */); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); } } var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); @@ -29168,32 +29762,47 @@ var ts; } return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148 /* Parameter */); - ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 292 /* JSDocParameterTag */); + } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; + var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - cloneBindingName(parameterDeclaration.name) : + parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 145 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -29213,7 +29822,7 @@ var ts; } } } - function lookupSymbolChain(symbol, context, meaning) { + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; @@ -29233,11 +29842,11 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent_10 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_10) { - var parentChain = getSymbolChain(parent_10, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { - parentSymbol = parent_10; + parentSymbol = parent; accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); } } @@ -29249,7 +29858,7 @@ var ts; // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; @@ -29281,22 +29890,54 @@ var ts; } return typeParameterNodes; } - function symbolToTypeNode(symbol, context, meaning) { - var chain = lookupSymbolChain(symbol, context, meaning); + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module context.flags |= 16777216 /* InInitialEntityName */; var rootName = getNameOfSymbolAsWritten(chain[0], context); context.flags ^= 16777216 /* InInitialEntityName */; var isTypeOf = meaning === 67216319 /* Value */; if (ambientModuleSymbolRegex.test(rootName)) { // module is root, must use `ImportTypeNode` - var nonRootParts = chain.length > 1 ? createEntityNameFromSymbolChain(chain, chain.length - 1, 1) : undefined; - var typeParameterNodes = lookupTypeParameterNodes(chain, 0, context); - return ts.createImportTypeNode(ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))), nonRootParts, typeParameterNodes, isTypeOf); + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))); + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } } - var entityName = createEntityNameFromSymbolChain(chain, chain.length - 1, 0); - return isTypeOf ? ts.createTypeQueryNode(entityName) : ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); - function createEntityNameFromSymbolChain(chain, index, stopper) { - var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; @@ -29305,9 +29946,27 @@ var ts; if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); identifier.symbol = symbol; - return index > stopper ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1, stopper), identifier) : identifier; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; } } function symbolToName(symbol, context, meaning, expectsIdentifier) { @@ -29456,10 +30115,28 @@ var ts; return "default"; } if (symbol.declarations && symbol.declarations.length) { + if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { + var file_3 = ts.getDeclarationOfKind(symbol, 273 /* SourceFile */); + if (!file_3 || !context.tracker.moduleResolverHost) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl); + } + } + } + // ambient module, just use declaration/symbol name (fallthrough) + } + else { + return "\"" + ts.getResolvedExternalModuleName(context.tracker.moduleResolverHost, file_3, ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration))) + "\""; + } + } var declaration = symbol.declarations[0]; - var name_16 = ts.getNameOfDeclaration(declaration); - if (name_16) { - return ts.declarationNameToString(name_16); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 231 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -29497,6 +30174,11 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); case 181 /* BindingElement */: return isDeclarationVisible(node.parent.parent); case 231 /* VariableDeclaration */: @@ -29517,14 +30199,14 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_11 = getDeclarationContainer(node); + var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 242 /* ImportEqualsDeclaration */ && parent_11.kind !== 273 /* SourceFile */ && parent_11.flags & 4194304 /* Ambient */)) { - return isGlobalSourceFile(parent_11); + !(node.kind !== 242 /* ImportEqualsDeclaration */ && parent.kind !== 273 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_11); + return isDeclarationVisible(parent); case 151 /* PropertyDeclaration */: case 150 /* PropertySignature */: case 155 /* GetAccessor */: @@ -29723,8 +30405,8 @@ var ts; var members = ts.createSymbolTable(); var names = ts.createUnderscoreEscapedMap(); for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var name_17 = properties_2[_i]; - names.set(ts.getTextOfPropertyName(name_17), true); + var name = properties_2[_i]; + names.set(ts.getTextOfPropertyName(name), true); } for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; @@ -29774,11 +30456,11 @@ var ts; } else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name_18 = declaration.propertyName || declaration.name; - var isLate = isLateBindableName(name_18); - var isWellKnown = ts.isComputedPropertyName(name_18) && ts.isWellKnownSymbolSyntactically(name_18.expression); - if (!isLate && !isWellKnown && isComputedNonLiteralName(name_18)) { - var exprType = checkExpression(name_18.expression); + var name = declaration.propertyName || declaration.name; + var isLate = isLateBindableName(name); + var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression); + if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { + var exprType = checkExpression(name.expression); if (isTypeAssignableToKind(exprType, 1536 /* ESSymbolLike */)) { if (noImplicitAny) { error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); @@ -29798,10 +30480,10 @@ var ts; } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - var nameType = isLate && checkComputedPropertyName(name_18); + var nameType = isLate && checkComputedPropertyName(name); var text = isLate ? getLateBoundNameFromType(nameType) : - isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name_18.expression.name)) : - ts.getTextOfPropertyName(name_18); + isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : + ts.getTextOfPropertyName(name); // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); @@ -29817,7 +30499,7 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { - error(name_18, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_18)); + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); return unknownType; } } @@ -30209,7 +30891,7 @@ var ts; if (symbol.flags & 4194304 /* Prototype */) { return links.type = getTypeOfPrototypeProperty(symbol); } - // CommonsJS require/module/exports all have type any. + // CommonsJS require and module both have type any. if (symbol === requireSymbol || symbol === moduleSymbol) { return links.type = anyType; } @@ -30219,6 +30901,10 @@ var ts; return links.type = anyType; } // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } if (declaration.kind === 248 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } @@ -30239,7 +30925,7 @@ var ts; declaration.kind === 184 /* PropertyAccessExpression */ && declaration.parent.kind === 199 /* BinaryExpression */) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else if (ts.isJSDocPropertyTag(declaration) + else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) || ts.isIdentifier(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) @@ -30510,13 +31196,15 @@ var ts; case 152 /* MethodSignature */: case 162 /* FunctionType */: case 163 /* ConstructorType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: case 233 /* FunctionDeclaration */: case 153 /* MethodDeclaration */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: case 236 /* TypeAliasDeclaration */: - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: case 176 /* MappedType */: case 170 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); @@ -30526,7 +31214,7 @@ var ts; else if (node.kind === 170 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 234 /* ClassDeclaration */ || node.kind === 204 /* ClassExpression */ || node.kind === 235 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; @@ -30545,13 +31233,12 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 235 /* InterfaceDeclaration */ || node.kind === 234 /* ClassDeclaration */ || - node.kind === 204 /* ClassExpression */ || node.kind === 236 /* TypeAliasDeclaration */) { + if (node.kind === 235 /* InterfaceDeclaration */ || + node.kind === 234 /* ClassDeclaration */ || + node.kind === 204 /* ClassExpression */ || + ts.isTypeAlias(node)) { var declaration = node; - var typeParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - if (typeParameters) { - result = appendTypeParameters(result, typeParameters); - } + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); } } return result; @@ -30828,9 +31515,9 @@ var ts; return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 292 /* JSDocTypedefTag */ || d.kind === 236 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 236 /* TypeAliasDeclaration */; }); - var typeNode = declaration.kind === 292 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { @@ -31035,7 +31722,7 @@ var ts; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && - (!typeParameters || typeParameters.every(isThislessTypeParameter)); + typeParameters.every(isThislessTypeParameter); } /** * Returns true if the class or interface member given by the symbol is free of "this" references. The @@ -31084,6 +31771,9 @@ var ts; var symbol = type.symbol; var members = getMembersOfSymbol(symbol); type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); @@ -31213,9 +31903,9 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_19 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_19); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_19); + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); } lateSymbol.nameType = type; @@ -31644,10 +32334,8 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var constraintDeclaration = type.declaration.typeParameter.constraint; var include = keyofStringsOnly ? 32 /* StringLiteral */ : 1120 /* StringOrNumberLiteralOrUnique */; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; @@ -31720,15 +32408,21 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : unknownType); } + function getConstraintDeclarationForMappedType(type) { + return type.declaration.typeParameter.constraint; + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); + return constraintDeclaration.kind === 174 /* TypeOperator */ && + constraintDeclaration.operator === 128 /* KeyOfKeyword */; + } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); } else { // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, @@ -31889,9 +32583,9 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(type.checkType); + var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); if (constraint) { - var mapper = createTypeMapper([type.root.checkType], [constraint]); + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 16384 /* Never */)) { return instantiated; @@ -32278,9 +32972,10 @@ var ts; // type checking functions). function getTypeParametersFromDeclaration(declaration) { var result; - ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); - }); + } return result; } function symbolsToArray(symbols) { @@ -32295,10 +32990,10 @@ var ts; function isJSDocOptionalParameter(node) { return ts.isInJavaScriptFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 280 /* JSDocOptionalType */ + node.type && node.type.kind === 282 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 280 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -32310,7 +33005,7 @@ var ts; return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -32327,6 +33022,13 @@ var ts; } return false; } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */; + } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); @@ -32384,7 +33086,7 @@ var ts; for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); @@ -32415,6 +33117,7 @@ var ts; for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); @@ -32427,12 +33130,13 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 177 /* LiteralType */) { + if (type && type.kind === 177 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || isUntypedSignatureInJSFile || isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { @@ -32466,7 +33170,7 @@ var ts; * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` */ function maybeAddJsSyntheticRestParameter(declaration, parameters) { - if (!containsArgumentsReference(declaration)) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { return false; } var lastParam = ts.lastOrUndefined(declaration.parameters); @@ -32611,9 +33315,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - var name_20 = ts.getNameOfDeclaration(declaration); - if (name_20) { - error(name_20, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name_20)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -32859,7 +33563,7 @@ var ts; var isJs = ts.isInJavaScriptFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 286 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && node.parent.kind !== 289 /* JSDocAugmentsTag */; var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -33010,15 +33714,15 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node)) { - var parent_12 = node.parent; - if (parent_12.kind === 170 /* ConditionalType */ && node === parent_12.trueType) { - var constraint = getImpliedConstraint(typeVariable, parent_12.checkType, parent_12.extendsType); + while (node && !ts.isStatement(node) && node.kind !== 285 /* JSDocComment */) { + var parent = node.parent; + if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) { + var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); } } - node = parent_12; + node = parent; } return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } @@ -33460,7 +34164,7 @@ var ts; includes & 4096 /* Undefined */ ? includes & 16777216 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 8374815 /* NotUnit */ ? 0 : 268435456 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -33497,7 +34201,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -33508,7 +34212,7 @@ var ts; var type = unionTypes.get(id); if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */); - type = createType(131072 /* Union */ | propagatedFlags); + type = createType(131072 /* Union */ | propagatedFlags | unionOfUnitTypes); unionTypes.set(id, type); type.types = types; /* @@ -33525,7 +34229,8 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -33574,6 +34279,31 @@ var ts; } } } + // When intersecting unions of unit types we can simply intersect based on type identity. + // Here we remove all unions of unit types from the given list and replace them with a + // a single union containing an intersection of the unit types. + function intersectUnionsOfUnitTypes(types) { + var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 268435456 /* UnionOfUnitTypes */) !== 0; }); + var unionType = types[unionIndex]; + var intersection = unionType.types; + var i = types.length - 1; + var _loop_5 = function () { + var t = types[i]; + if (t.flags & 268435456 /* UnionOfUnitTypes */) { + intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + ts.orderedRemoveItemAt(types, i); + } + i--; + }; + while (i > unionIndex) { + _loop_5(); + } + if (intersection === unionType.types) { + return false; + } + types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 268435456 /* UnionOfUnitTypes */); + return true; + } // We normalize combinations of intersection and union types based on the distributive property of the '&' // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection // types with union type constituents into equivalent union types with intersection type constituents and @@ -33608,6 +34338,12 @@ var ts; return typeSet[0]; } if (includes & 131072 /* Union */) { + if (includes & 268435456 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 131072 /* Union */) !== 0; }); @@ -33629,7 +34365,8 @@ var ts; function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -33648,9 +34385,9 @@ var ts; if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { - var name_21 = ts.getNameOfDeclaration(prop.valueDeclaration); - type = name_21 && ts.isNumericLiteral(name_21) ? getLiteralType(+name_21.text) : - name_21 && name_21.kind === 146 /* ComputedPropertyName */ && ts.isNumericLiteral(name_21.expression) ? getLiteralType(+name_21.expression.text) : + var name = ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : + name && name.kind === 146 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : getLiteralType(ts.symbolName(prop)); } if (type && type.flags & include) { @@ -33806,6 +34543,10 @@ var ts; // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // the type itself if no transformation is possible. function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; var objectType = type.objectType; if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) { // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or @@ -33824,7 +34565,7 @@ var ts; regularTypes.push(t); } } - return getUnionType([ + return type.simplified = getUnionType([ getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), getIntersectionType(stringIndexTypes) ]); @@ -33835,7 +34576,7 @@ var ts; // eventually anyway, but it easier to reason about. if (ts.some(objectType.types, isMappedTypeToNever)) { var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); } } // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper @@ -33843,15 +34584,15 @@ var ts; // construct the type Box. We do not further simplify the result because mapped types can be recursive // and we might never terminate. if (isGenericMappedType(objectType)) { - return substituteIndexedMappedType(objectType, type); + return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { - return substituteIndexedMappedType(constraint, type); + return type.simplified = substituteIndexedMappedType(constraint, type); } } - return type; + return type.simplified = type; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); @@ -33916,7 +34657,7 @@ var ts; var type = createObjectType(32 /* Mapped */, node.symbol); type.declaration = node; type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); links.resolvedType = type; // Eagerly resolve the constraint type which forces an error if the constraint type circularly // references itself through one or more type aliases. @@ -33939,14 +34680,14 @@ var ts; var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */); var combinedMapper; if (root.inferTypeParameters) { - var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + var context_1 = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); if (!isDeferred) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + inferTypes(context_1.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); } - combinedMapper = combineTypeMappers(mapper, context); + combinedMapper = combineTypeMappers(mapper, context_1); } if (!isDeferred) { // Return union of trueType and falseType for 'any' since it matches anything @@ -34017,7 +34758,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var checkType = getTypeFromTypeNode(node.checkType); - var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); var root = { @@ -34030,7 +34772,7 @@ var ts; inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, - aliasSymbol: getAliasSymbolForTypeNode(node), + aliasSymbol: aliasSymbol, aliasTypeArguments: aliasTypeArguments }; links.resolvedType = getConditionalType(root, /*mapper*/ undefined); @@ -34129,7 +34871,7 @@ var ts; else { var type = createObjectType(16 /* Anonymous */, node.symbol); type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { type = createArrayType(type); } @@ -34139,10 +34881,9 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 236 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); + function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } /** @@ -34321,8 +35062,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119 /* AnyKeyword */: - case 276 /* JSDocAllType */: - case 277 /* JSDocUnknownType */: + case 278 /* JSDocAllType */: + case 279 /* JSDocUnknownType */: return anyType; case 137 /* StringKeyword */: return stringType; @@ -34363,21 +35104,22 @@ var ts; return getTypeFromUnionTypeNode(node); case 169 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 278 /* JSDocNullableType */: + case 280 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 280 /* JSDocOptionalType */: + case 282 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); case 172 /* ParenthesizedType */: - case 279 /* JSDocNonNullableType */: - case 275 /* JSDocTypeExpression */: + case 281 /* JSDocNonNullableType */: + case 277 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); case 162 /* FunctionType */: case 163 /* ConstructorType */: case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: - case 281 /* JSDocFunctionType */: + case 286 /* JSDocTypeLiteral */: + case 283 /* JSDocFunctionType */: + case 287 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 174 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); @@ -34567,6 +35309,15 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; + if (ts.isInJavaScriptFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); if (isJavaScriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); @@ -34608,8 +35359,8 @@ var ts; // between the node and the type parameter declaration, if the node contains actual references to the // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_2 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_2; })) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_3; })) { return ts.forEachChild(node, containsReference); } } @@ -35459,7 +36210,7 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { + var _loop_6 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -35496,7 +36247,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_5(prop); + var state_3 = _loop_6(prop); if (typeof state_3 === "object") return state_3.value; } @@ -35802,16 +36553,19 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || constraint.flags & 1 /* Any */) { + if (!constraint || (source.flags & 32768 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~134217728 /* NonPrimitive */))) { errorInfo = saveErrorInfo; return result; } } - else if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var instantiated = getTypeWithThisArgument(constraint, source); + if (result = isRelatedTo(instantiated, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else if (source.flags & 524288 /* Index */) { @@ -35939,10 +36693,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_1; - if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -37646,15 +38400,15 @@ var ts; } function getBindingElementNameText(element) { if (element.parent.kind === 179 /* ObjectBindingPattern */) { - var name_22 = element.propertyName || element.name; - switch (name_22.kind) { + var name = element.propertyName || element.name; + switch (name.kind) { case 71 /* Identifier */: - return ts.idText(name_22); + return ts.idText(name); case 146 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteral(name_22.expression) ? name_22.expression.text : undefined; + return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return name_22.text; + return name.text; default: // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined ts.Debug.fail("Unexpected name kind for binding element name"); @@ -38049,7 +38803,7 @@ var ts; if (type.flags & 131072 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 268435456 /* UnionOfUnitTypes */); } return f(type) ? type : neverType; } @@ -39285,7 +40039,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 281 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 283 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -39532,14 +40286,14 @@ var ts; } // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. - var parent_13 = func.parent; - if (parent_13.kind === 199 /* BinaryExpression */ && parent_13.operatorToken.kind === 58 /* EqualsToken */) { - var target = parent_13.left; + var parent = func.parent; + if (parent.kind === 199 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + var target = parent.left; if (target.kind === 184 /* PropertyAccessExpression */ || target.kind === 185 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { - var sourceFile = ts.getSourceFileOfNode(parent_13); + var sourceFile = ts.getSourceFileOfNode(parent); if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { return undefined; } @@ -39621,11 +40375,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_23 = declaration.propertyName || declaration.name; + var name = declaration.propertyName || declaration.name; if (parentDeclaration.kind !== 181 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !ts.isBindingPattern(name_23)) { - var text = ts.getTextOfPropertyName(name_23); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); } @@ -39721,7 +40475,7 @@ var ts; // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? - getTypeOfExpression(left, /*cache*/ true) : type; + getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; @@ -40000,8 +40754,18 @@ var ts; return unknownType; } } - if (context.typeArguments) { - signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + var links = getNodeLinks(context); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(valueType); + var cachedResolved = links.resolvedSignatures.get(cacheKey); + if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { + signatures = cachedResolved; + } + else if (!cachedResolved) { + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); } return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); } @@ -40312,7 +41076,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 179 /* ObjectBindingPattern */ || contextualType.pattern.kind === 183 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; @@ -40908,6 +41672,37 @@ var ts; } return undefined; } + function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { + var links = getNodeLinks(openingLikeElement); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(elementType); + if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { + return; + } + else if (links.resolvedSignatures.get(cacheKey)) { + return links.resolvedSignatures.get(cacheKey); + } + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(elementType, 0 /* Call */); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + if (reportErrors) { + error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); + } + return; + } + } + // Instantiate in context of source type + var results = instantiateJsxSignatures(openingLikeElement, signatures); + links.resolvedSignatures.set(cacheKey, results); + return results; + } /** * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. * For instance: @@ -40963,19 +41758,10 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(elementType, 1 /* Construct */); - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(elementType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - return unknownType; - } + var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); + if (!ts.length(instantiatedSignatures)) { + return unknownType; } - // Instantiate in context of source type - var instantiatedSignatures = instantiateJsxSignatures(openingLikeElement, signatures); var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. @@ -41199,21 +41985,21 @@ var ts; // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span if (ts.length(openingLikeElement.attributes.properties)) { var reportedError = false; - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (ts.isJsxSpreadAttribute(prop)) return "continue"; - var name_24 = ts.idText(prop.name); - var sourcePropType = getIndexedAccessType(sourceAttributesType, getLiteralType(name_24)); - var targetPropType = getIndexedAccessType(targetAttributesType, getLiteralType(name_24)); + var name = ts.idText(prop.name); + var sourcePropType = getIndexedAccessType(sourceAttributesType, getLiteralType(name)); + var targetPropType = getIndexedAccessType(targetAttributesType, getLiteralType(name)); var rootChain = function () { return ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Types_of_property_0_are_incompatible, name_24); }; + /*details*/ undefined, ts.Diagnostics.Types_of_property_0_are_incompatible, name); }; if (!checkTypeAssignableTo(sourcePropType, targetPropType, prop, /*headMessage*/ undefined, rootChain)) { reportedError = true; } }; for (var _b = 0, _c = openingLikeElement.attributes.properties; _b < _c.length; _b++) { var prop = _c[_b]; - _loop_6(prop); + _loop_7(prop); } if (reportedError) { return; @@ -41252,9 +42038,9 @@ var ts; return true; } if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { - var parent_14 = symbol.valueDeclaration.parent; - return parent_14 && ts.isBinaryExpression(parent_14) && - ts.getSpecialPropertyAssignmentKind(parent_14) === 3 /* PrototypeProperty */; + var parent = symbol.valueDeclaration.parent; + return parent && ts.isBinaryExpression(parent) && + ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -41857,13 +42643,13 @@ var ts; for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_15 = signature.declaration && signature.declaration.parent; + var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_15 === lastParent) { + if (lastParent && parent === lastParent) { index++; } else { - lastParent = parent_15; + lastParent = parent; index = cutoffIndex; } } @@ -41871,7 +42657,7 @@ var ts; // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_15; + lastParent = parent; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -42484,10 +43270,10 @@ var ts; var isDecorator = node.kind === 149 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; - if (!isDecorator && !isJsxOpeningOrSelfClosingElement) { + if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (isTaggedTemplate || node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -43012,28 +43798,6 @@ var ts; */ function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); - return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - } - /** - * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. - * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible - * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. - * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures - */ - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) - if (elementType.flags & 131072 /* Union */) { - var types = elementType.types; - var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); - } - return result; - } var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); @@ -43053,7 +43817,18 @@ var ts; case 256 /* JsxOpeningElement */: case 255 /* JsxSelfClosingElement */: // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; + var exprTypes = checkExpression(node.tagName); + return forEachType(exprTypes, function (exprType) { + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + if (sfcResult && sfcResult !== unknownSignature) { + return sfcResult; + } + var sigs = getInstantiatedJsxSignatures(node, exprType); + if (candidatesOutArray && ts.length(sigs)) { + candidatesOutArray.push.apply(candidatesOutArray, sigs); + } + return ts.length(sigs) ? sigs[0] : unknownSignature; + }) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -43251,8 +44026,8 @@ var ts; if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); - var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + var file_4 = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file_4, originalSymbol, /*dontResolveAlias*/ false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); @@ -43706,7 +44481,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -43940,8 +44715,8 @@ var ts; } if (type.flags & 393216 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -44029,14 +44804,14 @@ var ts; /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { if (property.kind === 269 /* PropertyAssignment */ || property.kind === 270 /* ShorthandPropertyAssignment */) { - var name_25 = property.name; - if (name_25.kind === 146 /* ComputedPropertyName */) { - checkComputedPropertyName(name_25); + var name = property.name; + if (name.kind === 146 /* ComputedPropertyName */) { + checkComputedPropertyName(name); } - if (isComputedNonLiteralName(name_25)) { + if (isComputedNonLiteralName(name)) { return undefined; } - var text = ts.getTextOfPropertyName(name_25); + var text = ts.getTextOfPropertyName(name); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -44052,7 +44827,7 @@ var ts; } } else { - error(name_25, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_25)); + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } else if (property.kind === 271 /* SpreadAssignment */) { @@ -44384,11 +45159,11 @@ var ts; var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { - var name_26 = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name_26, 67901928 /* Type */, undefined, name_26, /*isUse*/ false); + var name = prop.escapedName; + var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); if (symbol) { - grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name_26)); - return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name_26)); + grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); } } } @@ -44919,9 +45694,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_27 = _a[_i].name; - if (ts.isBindingPattern(name_27) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_27, parameterName, typePredicate.parameterName)) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -44941,9 +45716,9 @@ var ts; case 162 /* FunctionType */: case 153 /* MethodDeclaration */: case 152 /* MethodSignature */: - var parent_16 = node.parent; - if (node === parent_16.type) { - return parent_16; + var parent = node.parent; + if (node === parent.type) { + return parent; } } } @@ -44953,13 +45728,13 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_28 = element.name; - if (name_28.kind === 71 /* Identifier */ && name_28.escapedText === predicateVariableName) { + var name = element.name; + if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_28.kind === 180 /* ArrayBindingPattern */ || name_28.kind === 179 /* ObjectBindingPattern */) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_28, predicateVariableNode, predicateVariableName)) { + else if (name.kind === 180 /* ArrayBindingPattern */ || name.kind === 179 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } } @@ -45036,7 +45811,7 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (node.kind !== 159 /* IndexSignature */ && node.kind !== 281 /* JSDocFunctionType */) { + if (node.kind !== 159 /* IndexSignature */ && node.kind !== 283 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -45499,7 +46274,7 @@ var ts; n.parent.kind !== 234 /* ClassDeclaration */ && n.parent.kind !== 204 /* ClassExpression */ && n.flags & 4194304 /* Ambient */) { - if (!(flags & 2 /* Ambient */)) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported flags |= 1 /* Export */; } @@ -45747,13 +46522,13 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); - var name_29 = ts.getNameOfDeclaration(d); + var name = ts.getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(name_29, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name_29)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(name_29, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name_29)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -45769,8 +46544,9 @@ var ts; switch (d.kind) { case 235 /* InterfaceDeclaration */: case 236 /* TypeAliasDeclaration */: - // A jsdoc typedef is, by definition, a type alias - case 292 /* JSDocTypedefTag */: + // A jsdoc typedef and callback are, by definition, type aliases + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: return 2 /* ExportType */; case 238 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ @@ -45792,10 +46568,10 @@ var ts; case 242 /* ImportEqualsDeclaration */: case 245 /* NamespaceImport */: case 244 /* ImportClause */: - var result_2 = 0 /* None */; + var result_3 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; case 231 /* VariableDeclaration */: case 181 /* BindingElement */: case 233 /* FunctionDeclaration */: @@ -46239,7 +47015,7 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDocTypedefTag(node) { + function checkJSDocTypeAliasTag(node) { if (!node.typeExpression) { // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); @@ -46363,7 +47139,13 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (potentiallyUnusedIdentifiers) { + if (produceDiagnostics) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } // TODO: GH#22580 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); potentiallyUnusedIdentifiers.push(node); @@ -46373,10 +47155,6 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 273 /* SourceFile */: - case 238 /* ModuleDeclaration */: - checkUnusedModuleMembers(node, addDiagnostic); - break; case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); @@ -46385,6 +47163,8 @@ var ts; case 235 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; + case 273 /* SourceFile */: + case 238 /* ModuleDeclaration */: case 212 /* Block */: case 240 /* CaseBlock */: case 219 /* ForStatement */: @@ -46417,33 +47197,6 @@ var ts; } } } - function checkUnusedLocalsAndParameters(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - node.locals.forEach(function (local) { - // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. - // If it's a type parameter merged with a parameter, check if the parameter-side is used. - if (local.flags & 262144 /* TypeParameter */ ? (local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : !local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148 /* Parameter */) { - var parameter = ts.getRootDeclaration(local.valueDeclaration); - var name_30 = ts.getNameOfDeclaration(local.valueDeclaration); - if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name_30)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name_30, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } - } - else { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local), addDiagnostic); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { @@ -46453,10 +47206,8 @@ var ts; return; } } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); - } + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -46504,7 +47255,7 @@ var ts; // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304 /* Ambient */) && typeParameters && ts.last(getSymbolOfNode(node).declarations) === node) { + if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { @@ -46513,50 +47264,91 @@ var ts; } } } - function checkUnusedModuleMembers(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. - var unusedImports_1 = ts.createMap(); - node.locals.forEach(function (local) { - if (local.isReferenced || local.exportSymbol) - return; - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isAmbientModule(declaration)) - continue; - if (isImportedDeclaration(declaration)) { - var importClause = importClauseFromImported(declaration); - var key = String(getNodeId(importClause)); - var group_1 = unusedImports_1.get(key); - if (group_1) { - group_1[1].push(declaration); - } - else { - unusedImports_1.set(key, [importClause, [declaration]]); + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + if (parameter) { + var name = ts.getNameOfDeclaration(local.valueDeclaration); + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { + addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); } } - }); - unusedImports_1.forEach(function (_a) { - var importClause = _a[0], unuseds = _a[1]; - var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { - for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { - var unused = unuseds_1[_i]; - errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); - } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } - else if (unuseds.length === 1) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else if (unuseds.length === 1) { + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else { + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } - else { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl))); - } - }); - } + } + else if (bindingElements.length === 1) { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + } + else { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + }); } function isImportedDeclaration(node) { return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */; @@ -46742,8 +47534,8 @@ var ts; // otherwise if variable has an initializer - show error that initialization will fail // since LHS will be block scoped name instead of function scoped if (!namesShareScope) { - var name_31 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_31, name_31); + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); } } } @@ -46844,14 +47636,14 @@ var ts; checkComputedPropertyName(node.propertyName); } // check private/protected variable access - var parent_17 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_17); - var name_32 = node.propertyName || node.name; - if (!ts.isBindingPattern(name_32)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_32)); + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + if (!ts.isBindingPattern(name)) { + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent_17.initializer && property) { - checkPropertyAccessibility(parent_17, parent_17.initializer, parentType, property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } } @@ -47716,10 +48508,10 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { // Report an error on every conflicting declaration. - var name_33 = symbolToString(symbol); + var name = symbolToString(symbol); for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name_33); + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } } @@ -47731,7 +48523,7 @@ var ts; var declaration = declarations_6[_i]; // If this declaration has too few or too many type parameters, we report an error var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - var numTypeParameters = ts.length(sourceParameters); + var numTypeParameters = sourceParameters.length; if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; } @@ -47879,7 +48671,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -47898,7 +48690,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -48230,16 +49022,16 @@ var ts; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { - var name_34; + var name = void 0; if (ex.kind === 184 /* PropertyAccessExpression */) { - name_34 = ex.name.escapedText; + name = ex.name.escapedText; } else { var argument = ex.argumentExpression; ts.Debug.assert(ts.isLiteralExpression(argument)); - name_34 = ts.escapeLeadingUnderscores(argument.text); + name = ts.escapeLeadingUnderscores(argument.text); } - return evaluateEnumMember(expr, type.symbol, name_34); + return evaluateEnumMember(expr, type.symbol, name); } } break; @@ -48456,9 +49248,9 @@ var ts; break; case 181 /* BindingElement */: case 231 /* VariableDeclaration */: - var name_35 = node.name; - if (ts.isBindingPattern(name_35)) { - for (var _b = 0, _c = name_35.elements; _b < _c.length; _b++) { + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); @@ -48747,9 +49539,9 @@ var ts; } } // Checks for export * conflicts - var exports = getExportsOfModule(moduleSymbol); - if (exports) { - exports.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -48855,27 +49647,28 @@ var ts; return checkInferType(node); case 178 /* ImportType */: return checkImportType(node); - case 286 /* JSDocAugmentsTag */: + case 289 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 292 /* JSDocTypedefTag */: - return checkJSDocTypedefTag(node); - case 288 /* JSDocParameterTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 292 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: checkSignatureDeclaration(node); // falls through - case 279 /* JSDocNonNullableType */: - case 278 /* JSDocNullableType */: - case 276 /* JSDocAllType */: - case 277 /* JSDocUnknownType */: - case 284 /* JSDocTypeLiteral */: + case 281 /* JSDocNonNullableType */: + case 280 /* JSDocNullableType */: + case 278 /* JSDocAllType */: + case 279 /* JSDocUnknownType */: + case 286 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 275 /* JSDocTypeExpression */: + case 277 /* JSDocTypeExpression */: return checkSourceElement(node.type); case 175 /* IndexedAccessType */: return checkIndexedAccessType(node); @@ -48987,8 +49780,8 @@ var ts; var paramTag = parent.parent; if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. - var host_2 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_2) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -48996,7 +49789,7 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_2.parameters); + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -49059,6 +49852,9 @@ var ts; return ts.Debug.assertNever(kind); } } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -49074,25 +49870,19 @@ var ts; ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); deferredNodes = []; - if (produceDiagnostics) { - ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName)); - allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []); - } ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { if (unusedIsError(kind)) { diagnostics.add(diag); } }); } deferredNodes = undefined; - seenPotentiallyUnusedIdentifiers.clear(); - potentiallyUnusedIdentifiers = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -49388,10 +50178,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 288 /* JSDocParameterTag */) { + if (entityName.parent.kind === 292 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 291 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 295 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -49931,6 +50721,7 @@ var ts; function isRequiredInitializedParameter(parameter) { return strictNullChecks && !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && parameter.initializer && !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } @@ -50082,9 +50873,9 @@ var ts; if (startInDeclarationContainer) { // When resolving the name of a declaration as a value, we need to start resolution // at a point outside of the declaration. - var parent_18 = reference.parent; - if (ts.isDeclaration(parent_18) && reference === parent_18.name) { - location = getDeclarationContainer(parent_18); + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); } } return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); @@ -50181,7 +50972,22 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, - getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); + var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 156 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 155 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 267 /* HeritageClause */; @@ -50217,8 +51023,8 @@ var ts; var decl = _a[_i]; // check meaning of the local symbol to see if declaration needs to be analyzed further if (decl.symbol && decl.symbol.flags & meaning) { - var file = ts.getSourceFileOfNode(decl); - var typeReferenceDirective = fileToDirective.get(file.path); + var file_5 = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file_5.path); if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } @@ -50239,9 +51045,9 @@ var ts; // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_19 = getParentOfSymbol(current); - if (parent_19) { - current = parent_19; + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; } else { break; @@ -50253,8 +51059,8 @@ var ts; // check that at least one declaration of top level symbol originates from type declaration file for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var file = ts.getSourceFileOfNode(decl); - if (fileToDirective.has(file.path)) { + var file_6 = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file_6.path)) { return true; } } @@ -50272,25 +51078,25 @@ var ts; function initializeTypeChecker() { // Bind all source files and propagate errors for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - ts.bindSourceFile(file, compilerOptions); + var file_7 = _a[_i]; + ts.bindSourceFile(file_7, compilerOptions); } // Initialize global symbol table var augmentations; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { - var file = _c[_b]; - if (!ts.isExternalOrCommonJsModule(file)) { - mergeSymbolTable(globals, file.locals); + var file_8 = _c[_b]; + if (!ts.isExternalOrCommonJsModule(file_8)) { + mergeSymbolTable(globals, file_8.locals); } - if (file.patternAmbientModules && file.patternAmbientModules.length) { - patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + if (file_8.patternAmbientModules && file_8.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file_8.patternAmbientModules); } - if (file.moduleAugmentations.length) { - (augmentations || (augmentations = [])).push(file.moduleAugmentations); + if (file_8.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file_8.moduleAugmentations); } - if (file.symbol && file.symbol.globalExports) { + if (file_8.symbol && file_8.symbol.globalExports) { // Merge in UMD exports with first-in-wins semantics (see #9771) - var source = file.symbol.globalExports; + var source = file_8.symbol.globalExports; source.forEach(function (sourceSymbol, id) { if (!globals.has(id)) { globals.set(id, sourceSymbol); @@ -50362,10 +51168,10 @@ var ts; var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { - var name_36 = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name_36), 67216319 /* Value */); + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); if (!symbol) { - error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name_36); + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } } } @@ -50742,7 +51548,7 @@ var ts; } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(ts.getEffectiveTypeParameterDeclarations(node), file); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { if (!ts.isArrowFunction(node)) { @@ -50928,10 +51734,10 @@ var ts; if (prop.kind === 271 /* SpreadAssignment */) { continue; } - var name_37 = prop.name; - if (name_37.kind === 146 /* ComputedPropertyName */) { + var name = prop.name; + if (name.kind === 146 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_37); + checkGrammarComputedPropertyName(name); } if (prop.kind === 270 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern @@ -50961,8 +51767,8 @@ var ts; case 270 /* ShorthandPropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_37.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name_37); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); } // falls through case 153 /* MethodDeclaration */: @@ -50977,7 +51783,7 @@ var ts; default: ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_37); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { continue; } @@ -50987,18 +51793,18 @@ var ts; } else { if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { - grammarErrorOnNode(name_37, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_37)); + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); } else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) { if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) { seen.set(effectiveName, currentKind | existingKind); } else { - return grammarErrorOnNode(name_37, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_37, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -51011,12 +51817,12 @@ var ts; if (attr.kind === 263 /* JsxSpreadAttribute */) { continue; } - var name_38 = attr.name, initializer = attr.initializer; - if (!seen.get(name_38.escapedText)) { - seen.set(name_38.escapedText, true); + var name = attr.name, initializer = attr.initializer; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); } else { - return grammarErrorOnNode(name_38, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } if (initializer && initializer.kind === 264 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); @@ -51126,10 +51932,10 @@ var ts; if (node.type.kind !== 138 /* SymbolKeyword */) { return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(138 /* SymbolKeyword */)); } - var parent_20 = ts.walkUpParenthesizedTypes(node.parent); - switch (parent_20.kind) { + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { case 231 /* VariableDeclaration */: - var decl = parent_20; + var decl = parent; if (decl.name.kind !== 71 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); } @@ -51137,18 +51943,18 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); } if (!(decl.parent.flags & 2 /* Const */)) { - return grammarErrorOnNode(parent_20.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; case 151 /* PropertyDeclaration */: - if (!ts.hasModifier(parent_20, 32 /* Static */) || - !ts.hasModifier(parent_20, 64 /* Readonly */)) { - return grammarErrorOnNode(parent_20.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + if (!ts.hasModifier(parent, 32 /* Static */) || + !ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; case 150 /* PropertySignature */: - if (!ts.hasModifier(parent_20, 64 /* Readonly */)) { - return grammarErrorOnNode(parent_20.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + if (!ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } break; default: @@ -51427,8 +52233,8 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + if (ts.isNodeArray(typeParameters)) { + var pos = typeParameters.pos, end = typeParameters.end; return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } @@ -51578,7 +52384,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -51657,10 +52463,8 @@ var ts; if (!elements || elements === ts.emptyArray) { elements = []; } - else { - if (ts.isNodeArray(elements)) { - return elements; - } + else if (ts.isNodeArray(elements)) { + return elements; } var array = elements; array.pos = -1; @@ -51720,6 +52524,13 @@ var ts; node.text = text; return node; } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; function createLiteralFromNode(sourceNode) { var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; @@ -51753,7 +52564,7 @@ var ts; recordTempVariable(name); } if (reservedInNestedScopes) { - name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; } return name; } @@ -51779,7 +52590,7 @@ var ts; /** Create a unique name based on the supplied text. */ function createOptimisticUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateFlags = 3 /* Unique */ | 32 /* Optimistic */; + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -51788,18 +52599,15 @@ var ts; /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ function createFileLevelUniqueName(text) { var name = createOptimisticUniqueName(text); - name.autoGenerateFlags |= 64 /* FileLevel */; + name.autoGenerateFlags |= 32 /* FileLevel */; return name; } ts.createFileLevelUniqueName = createFileLevelUniqueName; - function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { - var name = createIdentifier(""); - name.autoGenerateFlags = 4 /* Node */; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; name.autoGenerateId = nextAutoGenerateId; name.original = node; - if (shouldSkipNameGenerationScope) { - name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; - } nextAutoGenerateId++; return name; } @@ -51890,7 +52698,7 @@ var ts; ts.updateQualifiedName = updateQualifiedName; function parenthesizeForComputedName(expression) { return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) || - expression.kind === 297 /* CommaListExpression */ ? + expression.kind === 301 /* CommaListExpression */ ? createParen(expression) : expression; } @@ -52940,6 +53748,13 @@ var ts; return block; } ts.createBlock = createBlock; + /* @internal */ + function createExpressionStatement(expression) { + var node = createSynthesizedNode(215 /* ExpressionStatement */); + node.expression = expression; + return node; + } + ts.createExpressionStatement = createExpressionStatement; function updateBlock(node, statements) { return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) @@ -52966,9 +53781,7 @@ var ts; } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(215 /* ExpressionStatement */); - node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); - return node; + return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression)); } ts.createStatement = createStatement; function updateStatement(node, expression) { @@ -53864,7 +54677,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295 /* NotEmittedStatement */); + var node = createSynthesizedNode(299 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -53876,7 +54689,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(303 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -53888,7 +54701,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(302 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -53903,7 +54716,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(300 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -53919,7 +54732,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297 /* CommaListExpression */) { + if (node.kind === 301 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -53929,7 +54742,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297 /* CommaListExpression */); + var node = createSynthesizedNode(301 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -53940,15 +54753,31 @@ var ts; : node; } ts.updateCommaList = updateCommaList; - function createBundle(sourceFiles) { + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } var node = ts.createNode(274 /* Bundle */); + node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; - function updateBundle(node, sourceFiles) { - if (node.sourceFiles !== sourceFiles) { - return createBundle(sourceFiles); + function createUnparsedSourceFile(text) { + var node = ts.createNode(275 /* UnparsedSource */); + node.text = text; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration) { + var node = ts.createNode(276 /* InputFiles */); + node.javascriptText = javascript; + node.declarationText = declaration; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); } return node; } @@ -54220,6 +55049,15 @@ var ts; return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); } ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; /** * Gets the constant value to emit for an expression. */ @@ -54847,15 +55685,15 @@ var ts; function getName(node, allowComments, allowSourceMaps, emitFlags) { var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { - var name_39 = ts.getMutableClone(nodeName); + var name = ts.getMutableClone(nodeName); emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) emitFlags |= 1536 /* NoComments */; if (emitFlags) - ts.setEmitFlags(name_39, emitFlags); - return name_39; + ts.setEmitFlags(name, emitFlags); + return name; } return ts.getGeneratedNameForNode(node); } @@ -55192,7 +56030,7 @@ var ts; // if should be wrapped in parens since comma operator has the lowest precedence var emittedExpression = ts.skipPartiallyEmittedExpressions(e); return emittedExpression.kind === 199 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || - emittedExpression.kind === 297 /* CommaListExpression */ + emittedExpression.kind === 301 /* CommaListExpression */ ? ts.createParen(e) : e; } @@ -55212,7 +56050,7 @@ var ts; var check = ts.skipPartiallyEmittedExpressions(e); return (check.kind === 204 /* ClassExpression */ || check.kind === 191 /* FunctionExpression */ || - check.kind === 297 /* CommaListExpression */ || + check.kind === 301 /* CommaListExpression */ || ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */) ? ts.createParen(e) : e; @@ -55333,6 +56171,7 @@ var ts; switch (member.kind) { case 164 /* TypeQuery */: case 174 /* TypeOperator */: + case 171 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -55376,7 +56215,7 @@ var ts; case 184 /* PropertyAccessExpression */: node = node.expression; continue; - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -55406,7 +56245,7 @@ var ts; case 207 /* AsExpression */: case 208 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -55443,7 +56282,7 @@ var ts; case 189 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 207 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 208 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 300 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -55523,8 +56362,8 @@ var ts; function getLocalNameForExternalImport(node, sourceFile) { var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { - var name_40 = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name_40) ? name_40 : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name_40) || ts.idText(name_40)); + var name = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } if (node.kind === 243 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); @@ -55931,7 +56770,7 @@ var ts; statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements); } var declarations = context.endLexicalEnvironment(); - return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); } ts.visitLexicalEnvironment = visitLexicalEnvironment; /** @@ -56228,9 +57067,9 @@ var ts; case 273 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -56286,7 +57125,7 @@ var ts; case 214 /* EmptyStatement */: case 205 /* OmittedExpression */: case 230 /* DebuggerStatement */: - case 295 /* NotEmittedStatement */: + case 299 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -56665,10 +57504,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -56682,8 +57521,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements) - : ts.addRange(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + : ts.prependRange(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -56833,16 +57672,6 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; - function getNamedImportCount(node) { - if (!(node.importClause && node.importClause.namedBindings)) - return 0; - var names = node.importClause.namedBindings; - if (!names) - return 0; - if (!ts.isNamedImports(names)) - return 0; - return names.elements.length; - } function containsDefaultReference(node) { if (!node) return false; @@ -56853,12 +57682,40 @@ var ts; function isNamedDefaultReference(e) { return e.propertyName && e.propertyName.escapedText === "default" /* Default */; } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 273 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; function getImportNeedsImportStarHelper(node) { - return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); } ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { - return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -56905,10 +57762,10 @@ var ts; for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; if (!uniqueExports.get(ts.idText(specifier.name))) { - var name_41 = specifier.propertyName || specifier.name; - exportSpecifiers.add(ts.idText(name_41), specifier); - var decl = resolver.getReferencedImportDeclaration(name_41) - || resolver.getReferencedValueDeclaration(name_41); + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.idText(name), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); if (decl) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } @@ -56943,11 +57800,11 @@ var ts; } else { // export function x() { } - var name_42 = node.name; - if (!uniqueExports.get(ts.idText(name_42))) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name_42); - uniqueExports.set(ts.idText(name_42), true); - exportedNames = ts.append(exportedNames, name_42); + var name = node.name; + if (!uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); } } } @@ -56963,11 +57820,11 @@ var ts; } else { // export class x { } - var name_43 = node.name; - if (name_43 && !uniqueExports.get(ts.idText(name_43))) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name_43); - uniqueExports.set(ts.idText(name_43), true); - exportedNames = ts.append(exportedNames, name_43); + var name = node.name; + if (name && !uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); } } } @@ -57218,12 +58075,12 @@ var ts; } } for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { - var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name_44 = _a.name, value = _a.value, location_2 = _a.location, original = _a.original; - var variable = ts.createVariableDeclaration(name_44, + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name, /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; - ts.setTextRange(variable, location_2); - if (ts.isIdentifier(name_44)) { + ts.setTextRange(variable, location); + if (ts.isIdentifier(name)) { ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); } ts.aggregateTransformFlags(variable); @@ -57437,8 +58294,8 @@ var ts; return ts.createElementAccess(value, argumentExpression); } else { - var name_45 = ts.createIdentifier(ts.idText(propertyName)); - return ts.createPropertyAccess(value, name_45); + var name = ts.createIdentifier(ts.idText(propertyName)); + return ts.createPropertyAccess(value, name); } } /** @@ -57595,7 +58452,21 @@ var ts; * at the next execution site, in document order */ var pendingExpressions; - return transformSourceFile; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 274 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText); + } + return prepend; + })); + } /** * Transform TypeScript-specific syntax in a SourceFile. * @@ -58085,7 +58956,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, context.endLexicalEnvironment()); + ts.prependRange(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -58290,7 +59161,7 @@ var ts; // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); var alias = ts.getSynthesizedClone(temp); - alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent @@ -58567,7 +59438,7 @@ var ts; function transformInitializedProperty(property, receiver) { // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) - ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */))) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); @@ -59214,14 +60085,14 @@ var ts; case 71 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were // a source tree node for the purposes of the checker. - var name_46 = ts.getMutableClone(node); - name_46.flags &= ~8 /* Synthesized */; - name_46.original = undefined; - name_46.parent = ts.getParseTreeNode(currentScope); // ensure the parent is set to a parse tree node. + var name = ts.getMutableClone(node); + name.flags &= ~8 /* Synthesized */; + name.original = undefined; + name.parent = ts.getParseTreeNode(currentScope); // ensure the parent is set to a parse tree node. if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_46), ts.createLiteral("undefined")), name_46); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } - return name_46; + return name; case 145 /* QualifiedName */: return serializeQualifiedNameAsExpression(node, useFallback); } @@ -59597,6 +60468,11 @@ var ts; // we can safely elide the parentheses here, as a new synthetic // ParenthesizedExpression will be inserted if we remove parentheses too // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } return ts.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -59702,8 +60578,9 @@ var ts; currentNamespaceContainerName = localName; var statements = []; startLexicalEnvironment(); - ts.addRange(statements, ts.map(node.members, transformEnumMember)); - ts.addRange(statements, endLexicalEnvironment()); + var members = ts.map(node.members, transformEnumMember); + ts.prependRange(statements, endLexicalEnvironment()); + ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); @@ -59783,8 +60660,8 @@ var ts; */ function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name_47 = declaredNameInScope(node); - return currentScopeFirstDeclarationsOfName.get(name_47) === node; + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; } return true; } @@ -59943,7 +60820,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -60302,16 +61179,16 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2 /* NamespaceExports */) { - var name_48 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_48); + var name = node.name; + var exportedName = trySubstituteNamespaceExportedName(name); if (exportedName) { // A shorthand property with an assignment initializer is probably part of a // destructuring assignment if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.setTextRange(ts.createPropertyAssignment(name_48, initializer), node); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); } - return ts.setTextRange(ts.createPropertyAssignment(name_48, exportedName), node); + return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node); } } return node; @@ -60480,7 +61357,7 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -60752,7 +61629,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -60774,7 +61651,7 @@ var ts; var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); } else { result = expression; @@ -60964,7 +61841,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -61042,9 +61919,14 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -61346,7 +62228,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -61371,11 +62253,11 @@ var ts; statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); } ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); - var trailingStatements = endLexicalEnvironment(); - if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) { + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.prependRange(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); - ts.addRange(statements, trailingStatements); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } return body; @@ -61533,7 +62415,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -61550,7 +62432,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -61561,7 +62443,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -61575,7 +62457,7 @@ var ts; function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transform JSX-specific syntax in a SourceFile. * @@ -61793,12 +62675,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_49 = node.tagName; - if (ts.isIdentifier(name_49) && ts.isIntrinsicJsxName(name_49.escapedText)) { - return ts.createLiteral(ts.idText(name_49)); + var name = node.tagName; + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.idText(name)); } else { - return ts.createExpressionFromEntityName(name_49); + return ts.createExpressionFromEntityName(name); } } } @@ -62083,7 +62965,7 @@ var ts; (function (ts) { function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -62291,7 +63173,7 @@ var ts; * be reset. */ var enabledSubstitutions; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -62467,7 +63349,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -62721,7 +63603,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -62834,7 +63716,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -63018,17 +63900,17 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_50 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_50)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_50, initializer); + if (ts.isBindingPattern(name)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_50, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); } } } @@ -63469,6 +64351,7 @@ var ts; var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression); ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); statements.push(returnStatement); // To align with the source map emit for the old emitter, we set a custom @@ -63476,7 +64359,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); + ts.prependRange(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { @@ -64057,7 +64940,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.addRange(statements_4, lexicalEnvironment); + ts.prependRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -64510,10 +65393,12 @@ var ts; // We skip any outer expressions in a number of places to get to the innermost // expression, but we will restore them later to preserve comments and source maps. var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); - // The class statements are the statements generated by visiting the first statement of the + // The class statements are the statements generated by visiting the first statement with initializer of the // body (1), while all other statements are added to remainingStatements (2) - var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); - var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); // We know there is only one variable declaration here as we verified this in an // earlier call to isTypeScriptClassWrapper @@ -64523,6 +65408,7 @@ var ts; // we see as an assignment, for example: // // (function () { + // var C_1; // var C = C_1 = (function () { // function C() { // } @@ -64531,7 +65417,6 @@ var ts; // }()); // C = C_1 = __decorate([dec], C); // return C; - // var C_1; // }()) // var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); @@ -65161,7 +66046,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.enableSubstitution(184 /* PropertyAccessExpression */); context.enableSubstitution(269 /* PropertyAssignment */); - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. * @@ -65473,7 +66358,7 @@ var ts; var exceptionBlockStack; // A stack of containing exception blocks. var currentExceptionBlock; // The current exception block. var withBlockStack; // A stack containing `with` blocks. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; @@ -65730,7 +66615,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -66261,9 +67146,9 @@ var ts; function transformAndEmitVariableDeclarationList(node) { for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var variable = _a[_i]; - var name_51 = ts.getSynthesizedClone(variable.name); - ts.setCommentRange(name_51, variable.name); - hoistVariableDeclaration(name_51); + var name = ts.getSynthesizedClone(variable.name); + ts.setCommentRange(name, variable.name); + hoistVariableDeclaration(name); } var variables = ts.getInitializedVariables(node); var numVariables = variables.length; @@ -66844,9 +67729,9 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_52 = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; - if (name_52) { - var clone_6 = ts.getMutableClone(name_52); + var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; + if (name) { + var clone_6 = ts.getMutableClone(name); ts.setSourceMapRange(clone_6, node); ts.setCommentRange(clone_6, node); return clone_6; @@ -67923,7 +68808,7 @@ var ts; var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -67966,7 +68851,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -68189,7 +69074,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -68211,7 +69096,7 @@ var ts; */ function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); if (expressionResult) { if (emitAsReturn) { var statement = ts.createReturn(expressionResult); @@ -68252,29 +69137,84 @@ var ts; return visitFunctionDeclaration(node); case 234 /* ClassDeclaration */: return visitClassDeclaration(node); - case 298 /* MergeDeclarationMarker */: + case 302 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 303 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } - function importCallExpressionVisitor(node) { - // This visitor does not need to descend into the tree if there is no dynamic import, + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } else { - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 269 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 270 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 271 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 153 /* MethodDeclaration */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } function visitImportCallExpression(node) { - var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: @@ -68568,10 +69508,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -68585,13 +69525,13 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), - /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), /*location*/ node), /*original*/ node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -68613,10 +69553,10 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -68661,7 +69601,7 @@ var ts; } } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -68673,6 +69613,21 @@ var ts; } return ts.singleOrMany(statements); } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } /** * Transforms an exported variable with an initializer into an expression. * @@ -68680,13 +69635,13 @@ var ts; */ function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), /*visitor*/ undefined, context, 0 /* All */, - /*needsValue*/ false, createExportExpression); + /*needsValue*/ false, createAllExportExpressions); } else { return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), - /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); } } /** @@ -69059,8 +70014,8 @@ var ts; /*location*/ node); } else if (ts.isImportSpecifier(importDeclaration)) { - var name_53 = importDeclaration.propertyName || importDeclaration.name; - return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name_53)), + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), /*location*/ node); } } @@ -69090,8 +70045,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { - var exportName = exportedNames_1[_i]; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression, /*location*/ node); @@ -69127,8 +70082,8 @@ var ts; ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; - for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { - var exportName = exportedNames_2[_i]; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); @@ -69215,7 +70170,7 @@ var ts; var hoistedStatements; var enclosingBlockScopedContainer; var noSubstitution; // Set of nodes for which substitution rules should be ignored. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -69388,7 +70343,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -69518,12 +70473,12 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_2 = dependencyGroups_1[_i]; + var group_1 = dependencyGroups_1[_i]; // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -70116,9 +71071,9 @@ var ts; return visitCatchClause(node); case 212 /* Block */: return visitBlock(node); - case 298 /* MergeDeclarationMarker */: + case 302 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 303 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -70551,8 +71506,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { - var exportName = exportedNames_3[_i]; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } return expression; @@ -70585,8 +71540,8 @@ var ts; var expression = node.kind === 198 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; - for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { - var exportName = exportedNames_4[_i]; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } if (node.kind === 198 /* PostfixUnaryExpression */) { @@ -70653,7 +71608,7 @@ var ts; context.enableEmitNotification(273 /* SourceFile */); context.enableSubstitution(71 /* Identifier */); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -71160,7 +72115,12 @@ var ts; return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */; /** * Transforms a ts file into a .d.ts file * This process requires type information, which is retrieved through the emit resolver. Because of this, @@ -71180,19 +72140,22 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, - reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, }; var errorNameNode; var currentSourceFile; + var refs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); var noResolve = options.noResolve, stripInternal = options.stripInternal; - var host = context.getEmitHost(); return transformRoot; function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { if (!typeReferenceDirectives) { @@ -71204,6 +72167,10 @@ var ts; necessaryTypeRefernces.set(ref, true); } } + function trackReferencedAmbientModule(node) { + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } function handleSymbolAccessibilityError(symbolAccessibilityResult) { if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info @@ -71234,6 +72201,8 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } @@ -71277,12 +72246,16 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - return ts.updateSourceFileNode(sourceFile, filterCandidateImports(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText); + } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); @@ -71305,13 +72278,13 @@ var ts; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); necessaryTypeRefernces = undefined; - var refs = collectReferences(currentSourceFile, ts.createMap()); + refs = collectReferences(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); - refs.forEach(referenceVisitor); var statements = ts.visitNodes(node.statements, visitDeclarationStatements); - var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); @@ -71323,17 +72296,19 @@ var ts; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports - for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { - var importStatement = emittedImports_1[_i]; - if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { - var expr = importStatement.moduleReference.expression; - if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { return undefined; } } - else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { - return undefined; - } } return { fileName: typeName, pos: -1, end: -1 }; } @@ -71366,7 +72341,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); if (elem) { - ret.set("" + ts.getNodeId(elem), elem); + ret.set("" + ts.getOriginalNodeId(elem), elem); } }); return ret; @@ -71583,7 +72558,7 @@ var ts; } // Nothing visible } - function filterCandidateImports(statements) { + function transformAndReplaceLatePaintedStatements(statements) { // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during // error handling which must now be included in the output and themselves checked for errors. // For example: @@ -71598,62 +72573,45 @@ var ts; // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. - var unconsideredStatements = []; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); - if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope - unconsideredStatements.push(i); - continue; - } if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was foudn which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); - } - switch (i.kind) { - case 242 /* ImportEqualsDeclaration */: { - var result = transformImportEqualsDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 243 /* ImportDeclaration */: { - var result = transformImportDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 213 /* VariableStatement */: { - var result = transformVariableStatement(i, /*privateDeclaration*/ true); // Transform the statement (potentially again, possibly revealing more sub-nodes) - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - default: ts.Debug.assertNever(i, "Unhandled late painted statement!"); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } - // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not - // be considered in the child scope - lateMarkedStatements = unconsideredStatements; // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list // (and remove them from the set to examine for outter declarations) return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); - } - function visitLateVisibilityMarkedStatements(statement) { - if (ts.isLateVisibilityPaintedStatement(statement)) { - var key = "" + ts.getNodeId(statement); - if (lateStatementReplacementMap.has(key)) { - var result = lateStatementReplacementMap.get(key); - lateStatementReplacementMap.delete(key); - if (result && ts.isSourceFile(statement.parent) && !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */)) { - // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier - needsScopeFixMarker = true; + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; } - return result; } - else { - return ts.getParseTreeNode(statement) ? undefined : statement; - } - } - else { return statement; } } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } function visitDeclarationSubtree(input) { if (shouldStripInternal(input)) return; @@ -71851,13 +72809,21 @@ var ts; return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } - case 242 /* ImportEqualsDeclaration */: + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 242 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } case 243 /* ImportDeclaration */: { - // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later - // to reduce the likelihood we need to rewrite it - lateMarkedStatements = lateMarkedStatements || []; - ts.pushIfUnique(lateMarkedStatements, input); - return input; + return transformImportDeclaration(input); } } if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) @@ -71870,52 +72836,53 @@ var ts; previousEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = input; } - var previousNeedsDeclare; var canProdiceDiagnostic = ts.canProduceDiagnostics(input); var oldDiag = getSymbolAccessibilityDiagnostic; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); } - var oldPossibleImports; + var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 236 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(ts.updateTypeAliasDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 235 /* InterfaceDeclaration */: { return cleanup(ts.updateInterfaceDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 233 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type return cleanup(ts.updateFunctionDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), + /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); } case 238 /* ModuleDeclaration */: { - previousNeedsDeclare = needsDeclare; needsDeclare = false; - oldPossibleImports = lateMarkedStatements; - lateMarkedStatements = undefined; var inner = input.body; if (inner && inner.kind === 239 /* ModuleBlock */) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); - var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); return cleanup(ts.updateModuleDeclaration(input, /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); return cleanup(ts.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + /*decorators*/ undefined, mods, input.name, body)); } } case 234 /* ClassDeclaration */: { - var modifiers = ts.createNodeArray(ensureModifiers(input)); + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); var parameterProperties = void 0; @@ -71985,12 +72952,10 @@ var ts; } } case 213 /* VariableStatement */: { - var result = transformVariableStatement(input); - lateStatementReplacementMap.set("" + ts.getNodeId(input), result); // Don't actually elide yet; just leave as original node - will be elided/swapped by late pass - return cleanup(input); + return cleanup(transformVariableStatement(input, isPrivate)); } case 237 /* EnumDeclaration */: { - return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; // Rewrite enum values to their constants, if available @@ -72001,27 +72966,20 @@ var ts; } // Anything left unhandled is an error, so this should be unreachable return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); - function cleanup(returnValue) { + function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; } - if (input.kind === 238 /* ModuleDeclaration */) { - needsDeclare = previousNeedsDeclare; - lateMarkedStatements = ts.concatenate(oldPossibleImports, lateMarkedStatements); - } if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (returnValue && (!ts.isLateVisibilityPaintedStatement(input) || lateStatementReplacementMap.get("" + ts.getNodeId(input)))) { - if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) { - // Exported top-level member indicates moduleness - resultHasExternalModuleIndicator = true; - } + if (input.kind === 238 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; } - if (returnValue === input) { - return returnValue; + if (node === input) { + return node; } - return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } function transformVariableStatement(input, privateDeclaration) { @@ -72098,7 +73056,7 @@ var ts; return maskModifierFlags(node, mask, additions); } function ensureAccessor(node) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + var accessors = resolver.getAllAccessorDeclarations(node); if (node.kind !== accessors.firstAccessor.kind) { return; } @@ -72111,7 +73069,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -72125,7 +73083,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -72287,7 +73245,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(300 /* Count */); + var enabledSyntaxKindFeatures = new Array(304 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -72782,7 +73740,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 295 /* NotEmittedStatement */ + if (node.kind !== 299 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -72799,7 +73757,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 295 /* NotEmittedStatement */ + if (node.kind !== 299 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -72975,7 +73933,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 299 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -73299,6 +74257,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); /*@internal*/ /** @@ -73315,7 +74274,7 @@ var ts; var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var bundle = ts.createBundle(sourceFiles); + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; @@ -73341,7 +74300,8 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); @@ -73350,17 +74310,27 @@ var ts; var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } if (options.jsx === 1 /* Preserve */) { if (ts.isSourceFileJavaScript(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { @@ -73374,9 +74344,10 @@ var ts; } return ".js" /* Js */; } + ts.getOutputExtension = getOutputExtension; /*@internal*/ // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; @@ -73390,6 +74361,7 @@ var ts; mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, }); + var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; // Emit each output file ts.performance.mark("beforePrint"); @@ -73402,8 +74374,8 @@ var ts; sourceMaps: sourceMapDataList }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -73415,10 +74387,12 @@ var ts; if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } } - function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { - var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { // Make sure not to write js file and source map file if any of them cannot be written if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { emitSkipped = true; @@ -73428,7 +74402,7 @@ var ts; return; } // Transform the source files - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false); + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); // Create a printer to print the nodes var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { // resolver hooks @@ -73443,7 +74417,8 @@ var ts; // emitter hooks onSetSourceFile: setSourceFile, }); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); // Clean up emit nodes on parse tree transform.dispose(); } @@ -73454,8 +74429,8 @@ var ts; var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); - var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; - var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); if (ts.length(declarationTransform.diagnostics)) { for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { var diagnostic = _b[_a]; @@ -73477,17 +74452,18 @@ var ts; var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); } declarationTransform.dispose(); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 274 /* Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 273 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { - printer.writeBundle(bundle, writer); + printer.writeBundle(bundle, writer, bundleInfo); } else { printer.writeFile(sourceFile, writer); @@ -73503,9 +74479,15 @@ var ts; } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } // Reset state mapRecorder.reset(); writer.clear(); + bundleInfo = createDefaultBundleInfo(); } function setSourceFile(node) { sourceMap.setSourceFile(node); @@ -73515,6 +74497,13 @@ var ts; } } ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } @@ -73572,6 +74561,7 @@ var ts; switch (node.kind) { case 273 /* SourceFile */: return printFile(node); case 274 /* Bundle */: return printBundle(node); + case 275 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -73588,6 +74578,10 @@ var ts; writeFile(sourceFile, beginPrint()); return endPrint(); } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; setWriter(output); @@ -73605,7 +74599,7 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output) { + function writeBundle(bundle, output, bundleInfo) { isOwnFileEmit = false; var previousWriter = writer; setWriter(output); @@ -73613,13 +74607,28 @@ var ts; emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); - for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { - var sourceFile = _b[_a]; + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + writeLine(); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; print(0 /* SourceFile */, sourceFile, sourceFile); } reset(); writer = previousWriter; } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } function writeFile(sourceFile, output) { isOwnFileEmit = true; var previousWriter = writer; @@ -73642,7 +74651,8 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmitWithNotification(hint, node); + var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -73665,417 +74675,422 @@ var ts; comments.reset(); setWriter(/*output*/ undefined); } - // TODO: Should this just be `emit`? - // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034 - function emitIfPresent(node) { - if (node) { - emit(node); - } - } function emit(node) { - pipelineEmitWithNotification(4 /* Unspecified */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - pipelineEmitWithNotification(2 /* IdentifierName */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - pipelineEmitWithNotification(1 /* Expression */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, hint) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Comments */: + if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + return pipelineEmitWithComments; + } + return pipelineEmitWithoutComments; + case 2 /* SourceMaps */: + if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { + return pipelineEmitWithSourceMap; + } + // falls through + case 3 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + } + } + function getNextPipelinePhase(currentPhase, hint) { + return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - if (onEmitNode) { - onEmitNode(hint, node, pipelineEmitWithComments); - } - else { - pipelineEmitWithComments(hint, node); - } + ts.Debug.assertDefined(onEmitNode); + onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); } function pipelineEmitWithComments(hint, node) { - node = trySubstituteNode(hint, node); - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { - emitNodeWithComments(hint, node, pipelineEmitWithSourceMap); - } - else { - pipelineEmitWithSourceMap(hint, node); - } + ts.Debug.assertDefined(emitNodeWithComments); + ts.Debug.assert(hint !== 0 /* SourceFile */); + emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); + } + function pipelineEmitWithoutComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); + pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); - } - else { - pipelineEmitWithHint(hint, node); - } + ts.Debug.assertDefined(onEmitSourceMapOfNode); + ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */); + onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { - switch (hint) { - case 0 /* SourceFile */: return pipelineEmitSourceFile(node); - case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node); - case 1 /* Expression */: return pipelineEmitExpression(node); - case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 4 /* Unspecified */: return pipelineEmitUnspecified(node); + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + return emitLiteral(node); + case 275 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 145 /* QualifiedName */: + return emitQualifiedName(node); + case 146 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 147 /* TypeParameter */: + return emitTypeParameter(node); + case 148 /* Parameter */: + return emitParameter(node); + case 149 /* Decorator */: + return emitDecorator(node); + // Type members + case 150 /* PropertySignature */: + return emitPropertySignature(node); + case 151 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 152 /* MethodSignature */: + return emitMethodSignature(node); + case 153 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 154 /* Constructor */: + return emitConstructor(node); + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 157 /* CallSignature */: + return emitCallSignature(node); + case 158 /* ConstructSignature */: + return emitConstructSignature(node); + case 159 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 160 /* TypePredicate */: + return emitTypePredicate(node); + case 161 /* TypeReference */: + return emitTypeReference(node); + case 162 /* FunctionType */: + return emitFunctionType(node); + case 283 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 163 /* ConstructorType */: + return emitConstructorType(node); + case 164 /* TypeQuery */: + return emitTypeQuery(node); + case 165 /* TypeLiteral */: + return emitTypeLiteral(node); + case 166 /* ArrayType */: + return emitArrayType(node); + case 167 /* TupleType */: + return emitTupleType(node); + case 168 /* UnionType */: + return emitUnionType(node); + case 169 /* IntersectionType */: + return emitIntersectionType(node); + case 170 /* ConditionalType */: + return emitConditionalType(node); + case 171 /* InferType */: + return emitInferType(node); + case 172 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 206 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 173 /* ThisType */: + return emitThisType(); + case 174 /* TypeOperator */: + return emitTypeOperator(node); + case 175 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 176 /* MappedType */: + return emitMappedType(node); + case 177 /* LiteralType */: + return emitLiteralType(node); + case 178 /* ImportType */: + return emitImportTypeNode(node); + case 278 /* JSDocAllType */: + write("*"); + return; + case 279 /* JSDocUnknownType */: + write("?"); + return; + case 280 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 281 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 282 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 284 /* JSDocVariadicType */: + return emitJSDocVariadicType(node); + // Binding patterns + case 179 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 180 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 181 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 210 /* TemplateSpan */: + return emitTemplateSpan(node); + case 211 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 212 /* Block */: + return emitBlock(node); + case 213 /* VariableStatement */: + return emitVariableStatement(node); + case 214 /* EmptyStatement */: + return emitEmptyStatement(); + case 215 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 216 /* IfStatement */: + return emitIfStatement(node); + case 217 /* DoStatement */: + return emitDoStatement(node); + case 218 /* WhileStatement */: + return emitWhileStatement(node); + case 219 /* ForStatement */: + return emitForStatement(node); + case 220 /* ForInStatement */: + return emitForInStatement(node); + case 221 /* ForOfStatement */: + return emitForOfStatement(node); + case 222 /* ContinueStatement */: + return emitContinueStatement(node); + case 223 /* BreakStatement */: + return emitBreakStatement(node); + case 224 /* ReturnStatement */: + return emitReturnStatement(node); + case 225 /* WithStatement */: + return emitWithStatement(node); + case 226 /* SwitchStatement */: + return emitSwitchStatement(node); + case 227 /* LabeledStatement */: + return emitLabeledStatement(node); + case 228 /* ThrowStatement */: + return emitThrowStatement(node); + case 229 /* TryStatement */: + return emitTryStatement(node); + case 230 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 231 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 232 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 233 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 234 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 235 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 236 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 237 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 238 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 239 /* ModuleBlock */: + return emitModuleBlock(node); + case 240 /* CaseBlock */: + return emitCaseBlock(node); + case 241 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 242 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 243 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 244 /* ImportClause */: + return emitImportClause(node); + case 245 /* NamespaceImport */: + return emitNamespaceImport(node); + case 246 /* NamedImports */: + return emitNamedImports(node); + case 247 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 248 /* ExportAssignment */: + return emitExportAssignment(node); + case 249 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 250 /* NamedExports */: + return emitNamedExports(node); + case 251 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 252 /* MissingDeclaration */: + return; + // Module references + case 253 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 10 /* JsxText */: + return emitJsxText(node); + case 256 /* JsxOpeningElement */: + case 259 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 257 /* JsxClosingElement */: + case 260 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 261 /* JsxAttribute */: + return emitJsxAttribute(node); + case 262 /* JsxAttributes */: + return emitJsxAttributes(node); + case 263 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 264 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 265 /* CaseClause */: + return emitCaseClause(node); + case 266 /* DefaultClause */: + return emitDefaultClause(node); + case 267 /* HeritageClause */: + return emitHeritageClause(node); + case 268 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 269 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 270 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 271 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 272 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (ignored) + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + node = trySubstituteNode(1 /* Expression */, node); + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + return emitNumericLiteral(node); + case 9 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 97 /* SuperKeyword */: + case 101 /* TrueKeyword */: + case 99 /* ThisKeyword */: + case 91 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 182 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 183 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 184 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 185 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 186 /* CallExpression */: + return emitCallExpression(node); + case 187 /* NewExpression */: + return emitNewExpression(node); + case 188 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 189 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 190 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 191 /* FunctionExpression */: + return emitFunctionExpression(node); + case 192 /* ArrowFunction */: + return emitArrowFunction(node); + case 193 /* DeleteExpression */: + return emitDeleteExpression(node); + case 194 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 195 /* VoidExpression */: + return emitVoidExpression(node); + case 196 /* AwaitExpression */: + return emitAwaitExpression(node); + case 197 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 198 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 199 /* BinaryExpression */: + return emitBinaryExpression(node); + case 200 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 201 /* TemplateExpression */: + return emitTemplateExpression(node); + case 202 /* YieldExpression */: + return emitYieldExpression(node); + case 203 /* SpreadElement */: + return emitSpreadExpression(node); + case 204 /* ClassExpression */: + return emitClassExpression(node); + case 205 /* OmittedExpression */: + return; + case 207 /* AsExpression */: + return emitAsExpression(node); + case 208 /* NonNullExpression */: + return emitNonNullExpression(node); + case 209 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 254 /* JsxElement */: + return emitJsxElement(node); + case 255 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 258 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 300 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 301 /* CommaListExpression */: + return emitCommaList(node); + } } - } - function pipelineEmitSourceFile(node) { - ts.Debug.assertNode(node, ts.isSourceFile); - emitSourceFile(node); - } - function pipelineEmitIdentifierName(node) { - ts.Debug.assertNode(node, ts.isIdentifier); - emitIdentifier(node); } function emitMappedTypeParameter(node) { emit(node.name); writeSpace(); writeKeyword("in"); writeSpace(); - emitIfPresent(node.constraint); - } - function pipelineEmitUnspecified(node) { - var kind = node.kind; - // Reserved words - // Strict mode reserved words - // Contextual keywords - if (ts.isKeyword(kind)) { - writeTokenNode(node, writeKeyword); - return; - } - switch (kind) { - // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Parse tree nodes - // Names - case 145 /* QualifiedName */: - return emitQualifiedName(node); - case 146 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 147 /* TypeParameter */: - return emitTypeParameter(node); - case 148 /* Parameter */: - return emitParameter(node); - case 149 /* Decorator */: - return emitDecorator(node); - // Type members - case 150 /* PropertySignature */: - return emitPropertySignature(node); - case 151 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 152 /* MethodSignature */: - return emitMethodSignature(node); - case 153 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 154 /* Constructor */: - return emitConstructor(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 157 /* CallSignature */: - return emitCallSignature(node); - case 158 /* ConstructSignature */: - return emitConstructSignature(node); - case 159 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 160 /* TypePredicate */: - return emitTypePredicate(node); - case 161 /* TypeReference */: - return emitTypeReference(node); - case 162 /* FunctionType */: - return emitFunctionType(node); - case 281 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 163 /* ConstructorType */: - return emitConstructorType(node); - case 164 /* TypeQuery */: - return emitTypeQuery(node); - case 165 /* TypeLiteral */: - return emitTypeLiteral(node); - case 166 /* ArrayType */: - return emitArrayType(node); - case 167 /* TupleType */: - return emitTupleType(node); - case 168 /* UnionType */: - return emitUnionType(node); - case 169 /* IntersectionType */: - return emitIntersectionType(node); - case 170 /* ConditionalType */: - return emitConditionalType(node); - case 171 /* InferType */: - return emitInferType(node); - case 172 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 206 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 173 /* ThisType */: - return emitThisType(); - case 174 /* TypeOperator */: - return emitTypeOperator(node); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 176 /* MappedType */: - return emitMappedType(node); - case 177 /* LiteralType */: - return emitLiteralType(node); - case 178 /* ImportType */: - return emitImportTypeNode(node); - case 276 /* JSDocAllType */: - write("*"); - return; - case 277 /* JSDocUnknownType */: - write("?"); - return; - case 278 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 279 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 280 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 282 /* JSDocVariadicType */: - return emitJSDocVariadicType(node); - // Binding patterns - case 179 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 180 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 181 /* BindingElement */: - return emitBindingElement(node); - // Misc - case 210 /* TemplateSpan */: - return emitTemplateSpan(node); - case 211 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Statements - case 212 /* Block */: - return emitBlock(node); - case 213 /* VariableStatement */: - return emitVariableStatement(node); - case 214 /* EmptyStatement */: - return emitEmptyStatement(); - case 215 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 216 /* IfStatement */: - return emitIfStatement(node); - case 217 /* DoStatement */: - return emitDoStatement(node); - case 218 /* WhileStatement */: - return emitWhileStatement(node); - case 219 /* ForStatement */: - return emitForStatement(node); - case 220 /* ForInStatement */: - return emitForInStatement(node); - case 221 /* ForOfStatement */: - return emitForOfStatement(node); - case 222 /* ContinueStatement */: - return emitContinueStatement(node); - case 223 /* BreakStatement */: - return emitBreakStatement(node); - case 224 /* ReturnStatement */: - return emitReturnStatement(node); - case 225 /* WithStatement */: - return emitWithStatement(node); - case 226 /* SwitchStatement */: - return emitSwitchStatement(node); - case 227 /* LabeledStatement */: - return emitLabeledStatement(node); - case 228 /* ThrowStatement */: - return emitThrowStatement(node); - case 229 /* TryStatement */: - return emitTryStatement(node); - case 230 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 231 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 232 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 233 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 234 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 235 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 236 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 237 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 238 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 239 /* ModuleBlock */: - return emitModuleBlock(node); - case 240 /* CaseBlock */: - return emitCaseBlock(node); - case 241 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 242 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 243 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 244 /* ImportClause */: - return emitImportClause(node); - case 245 /* NamespaceImport */: - return emitNamespaceImport(node); - case 246 /* NamedImports */: - return emitNamedImports(node); - case 247 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 248 /* ExportAssignment */: - return emitExportAssignment(node); - case 249 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 250 /* NamedExports */: - return emitNamedExports(node); - case 251 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 252 /* MissingDeclaration */: - return; - // Module references - case 253 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX (non-expression) - case 10 /* JsxText */: - return emitJsxText(node); - case 256 /* JsxOpeningElement */: - case 259 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 257 /* JsxClosingElement */: - case 260 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 261 /* JsxAttribute */: - return emitJsxAttribute(node); - case 262 /* JsxAttributes */: - return emitJsxAttributes(node); - case 263 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 264 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 265 /* CaseClause */: - return emitCaseClause(node); - case 266 /* DefaultClause */: - return emitDefaultClause(node); - case 267 /* HeritageClause */: - return emitHeritageClause(node); - case 268 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 269 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 270 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 271 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 272 /* EnumMember */: - return emitEnumMember(node); - // JSDoc nodes (ignored) - // Transformation nodes (ignored) - } - // If the node is an expression, try to emit it as an expression with - // substitution. - if (ts.isExpression(node)) { - return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); - } - if (ts.isToken(node)) { - writeTokenNode(node, writePunctuation); - return; - } - } - function pipelineEmitExpression(node) { - var kind = node.kind; - switch (kind) { - // Literals - case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; - // Expressions - case 182 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 183 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 184 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 185 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 186 /* CallExpression */: - return emitCallExpression(node); - case 187 /* NewExpression */: - return emitNewExpression(node); - case 188 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 189 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 190 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 191 /* FunctionExpression */: - return emitFunctionExpression(node); - case 192 /* ArrowFunction */: - return emitArrowFunction(node); - case 193 /* DeleteExpression */: - return emitDeleteExpression(node); - case 194 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 195 /* VoidExpression */: - return emitVoidExpression(node); - case 196 /* AwaitExpression */: - return emitAwaitExpression(node); - case 197 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 198 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 199 /* BinaryExpression */: - return emitBinaryExpression(node); - case 200 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 201 /* TemplateExpression */: - return emitTemplateExpression(node); - case 202 /* YieldExpression */: - return emitYieldExpression(node); - case 203 /* SpreadElement */: - return emitSpreadExpression(node); - case 204 /* ClassExpression */: - return emitClassExpression(node); - case 205 /* OmittedExpression */: - return; - case 207 /* AsExpression */: - return emitAsExpression(node); - case 208 /* NonNullExpression */: - return emitNonNullExpression(node); - case 209 /* MetaProperty */: - return emitMetaProperty(node); - // JSX - case 254 /* JsxElement */: - return emitJsxElement(node); - case 255 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 258 /* JsxFragment */: - return emitJsxFragment(node); - // Transformation nodes - case 296 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 297 /* CommaListExpression */: - return emitCommaList(node); - } + emit(node.constraint); } function trySubstituteNode(hint, node) { return node && substituteNode && substituteNode(hint, node) || node; @@ -74151,6 +75166,10 @@ var ts; writeStringLiteral(text); } } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + write(unparsed.text); + } // // Identifiers // @@ -74201,13 +75220,11 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.dotDotDotToken); - if (node.name) { - emitNodeWithWriter(node.name, writeParameter); - } - emitIfPresent(node.questionToken); - if (node.parent && node.parent.kind === 281 /* JSDocFunctionType */ && !node.name) { - emitIfPresent(node.type); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 283 /* JSDocFunctionType */ && !node.name) { + emit(node.type); } else { emitTypeAnnotation(node.type); @@ -74226,7 +75243,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeAnnotation(node.type); writeSemicolon(); } @@ -74234,28 +75251,30 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); - emitIfPresent(node.exclamationToken); + emit(node.questionToken); + emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -74272,14 +75291,17 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitCallSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitConstructSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("new"); @@ -74288,6 +75310,7 @@ var ts; emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); @@ -74314,18 +75337,20 @@ var ts; emitTypeArguments(node, node.typeArguments); } function emitFunctionType(node) { + pushNameGenerationScope(node); emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitJSDocFunctionType(node) { write("function"); emitParameters(node, node.parameters); write(":"); - emitIfPresent(node.type); + emit(node.type); } function emitJSDocNullableType(node) { write("?"); @@ -74340,6 +75365,7 @@ var ts; write("="); } function emitConstructorType(node) { + pushNameGenerationScope(node); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -74347,7 +75373,8 @@ var ts; writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitTypeQuery(node) { writeKeyword("typeof"); @@ -74437,7 +75464,8 @@ var ts; writeSpace(); } writePunctuation("["); - pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); @@ -74447,7 +75475,7 @@ var ts; } writePunctuation(":"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); writeSemicolon(); if (emitFlags & 1 /* SingleLine */) { writeSpace(); @@ -74490,7 +75518,7 @@ var ts; writePunctuation("]"); } function emitBindingElement(node) { - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); if (node.propertyName) { emit(node.propertyName); writePunctuation(":"); @@ -74508,6 +75536,7 @@ var ts; emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); @@ -74597,6 +75626,7 @@ var ts; emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { @@ -74696,7 +75726,7 @@ var ts; } function emitYieldExpression(node) { emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { @@ -74704,6 +75734,7 @@ var ts; emitExpression(node.expression); } function emitClassExpression(node) { + generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { @@ -74757,7 +75788,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - writeSemicolon(); + if (!ts.isJsonSourceFile(currentSourceFile)) { + writeSemicolon(); + } } function emitIfStatement(node) { var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); @@ -74953,7 +75986,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -74970,6 +76003,8 @@ var ts; increaseIndent(); } pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); emitSignatureHead(node); if (onEmitNode) { onEmitNode(4 /* Unspecified */, body, emitBlockCallback); @@ -75065,6 +76100,7 @@ var ts; emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("class"); @@ -75142,6 +76178,7 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); popNameGenerationScope(node); } @@ -75183,12 +76220,12 @@ var ts; writeSemicolon(); } function emitImportClause(node) { - emitIfPresent(node.name); + emit(node.name); if (node.name && node.namedBindings) { emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } - emitIfPresent(node.namedBindings); + emit(node.namedBindings); } function emitNamespaceImport(node) { var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); @@ -75330,7 +76367,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { writePunctuation("{"); - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); emitExpression(node.expression); writePunctuation("}"); } @@ -75486,8 +76523,8 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { - var directive = types_18[_d]; + for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { + var directive = types_17[_d]; write("/// "); writeLine(); } @@ -75495,6 +76532,7 @@ var ts; function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); @@ -75571,6 +76609,8 @@ var ts; // Helpers // function emitNodeWithWriter(node, writer) { + if (!node) + return; var savedWrite = write; write = writer; emit(node); @@ -76060,7 +77100,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return generateName(node); } - else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { @@ -76112,6 +77152,113 @@ var ts; } reservedNames.set(name, true); } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 212 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 227 /* LabeledStatement */: + case 225 /* WithStatement */: + case 217 /* DoStatement */: + case 218 /* WhileStatement */: + generateNames(node.statement); + break; + case 216 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 219 /* ForStatement */: + case 221 /* ForOfStatement */: + case 220 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 226 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 240 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 265 /* CaseClause */: + case 266 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 229 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 268 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 213 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 232 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 231 /* VariableDeclaration */: + case 148 /* Parameter */: + case 181 /* BindingElement */: + case 234 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 233 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 179 /* ObjectBindingPattern */: + case 180 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 243 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 244 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 245 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 246 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 247 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 269 /* PropertyAssignment */: + case 270 /* ShorthandPropertyAssignment */: + case 151 /* PropertyDeclaration */: + case 153 /* MethodDeclaration */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } /** * Generate the text for a generated identifier. */ @@ -76119,17 +77266,7 @@ var ts; if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { - var savedTempFlags = tempFlags; - popNameGenerationScope(/*node*/ undefined); - var result = generateNameCached(getNodeForGeneratedName(name)); - pushNameGenerationScope(/*node*/ undefined); - tempFlags = savedTempFlags; - return result; - } - else { - return generateNameCached(getNodeForGeneratedName(name)); - } + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); } else { // Auto, Loop, and Unique names are cached based on their unique @@ -76138,9 +77275,9 @@ var ts; return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } - function generateNameCached(node) { + function generateNameCached(node, flags) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); } /** * Returns a value indicating whether a name is unique globally, within the current file, @@ -76155,7 +77292,7 @@ var ts; * Returns a value indicating whether a name is unique globally or within the current file. */ function isFileLevelUniqueName(name) { - return ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName); + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; } /** * Returns a value indicating whether a name is unique within a container. @@ -76179,13 +77316,13 @@ var ts; */ function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { - var name_54 = flags === 268435456 /* _i */ ? "_i" : "_n"; - if (isUniqueName(name_54)) { + var name = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name)) { tempFlags |= flags; if (reservedInNestedScopes) { - reserveNameInNestedScopes(name_54); + reserveNameInNestedScopes(name); } - return name_54; + return name; } } while (true) { @@ -76193,14 +77330,14 @@ var ts; tempFlags++; // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - var name_55 = count < 26 + var name = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_55)) { + if (isUniqueName(name)) { if (reservedInNestedScopes) { - reserveNameInNestedScopes(name_55); + reserveNameInNestedScopes(name); } - return name_55; + return name; } } } @@ -76212,11 +77349,16 @@ var ts; * makeUniqueName are guaranteed to never conflict. * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName, checkFn, optimistic) { + function makeUniqueName(baseName, checkFn, optimistic, scoped) { if (checkFn === void 0) { checkFn = isUniqueName; } if (optimistic) { if (checkFn(baseName)) { - generatedNames.set(baseName, true); + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } return baseName; } } @@ -76228,7 +77370,12 @@ var ts; while (true) { var generatedName = baseName + i; if (checkFn(generatedName)) { - generatedNames.set(generatedName, true); + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } return generatedName; } i++; @@ -76275,10 +77422,10 @@ var ts; /** * Generates a unique name from a node. */ - function generateNameForNode(node) { + function generateNameForNode(node, flags) { switch (node.kind) { case 71 /* Identifier */: - return makeUniqueName(getTextOfNode(node)); + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); case 238 /* ModuleDeclaration */: case 237 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); @@ -76305,11 +77452,11 @@ var ts; function makeName(name) { switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 3 /* Unique */: - return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 64 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 32 /* Optimistic */)); + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -76325,7 +77472,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateFlags === 4 /* Node */ + && !!(node.autoGenerateFlags & 4 /* Node */) && node.autoGenerateId !== autoGenerateId) { break; } @@ -76384,7 +77531,7 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); } function getCachedFileSystemEntriesForBaseDir(path) { return getCachedFileSystemEntries(ts.getDirectoryPath(path)); @@ -76397,7 +77544,7 @@ var ts; files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], directories: host.getDirectories(rootDir) || [] }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); return resultFromHost; } /** @@ -76406,6 +77553,7 @@ var ts; * The host request is done under try catch block to avoid caching incorrect result */ function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); var cachedResult = getCachedFileSystemEntries(rootDirPath); if (cachedResult) { return cachedResult; @@ -76415,7 +77563,7 @@ var ts; } catch (_e) { // If there is exception to read directories, dont cache the result and direct the calls to host - ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); return undefined; } } @@ -76451,7 +77599,7 @@ var ts; } function directoryExists(dirPath) { var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); } function createDirectory(dirPath) { var path = toPath(dirPath); @@ -76725,7 +77873,7 @@ var ts; if (!commonPathComponents) { // Can happen when all input files are .d.ts files return currentDirectory; } - return ts.getNormalizedPathFromPathComponents(commonPathComponents); + return ts.getPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { @@ -76832,7 +77980,8 @@ var ts; directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, - realpath: realpath + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); } }; } ts.createCompilerHost = createCompilerHost; @@ -76900,52 +78049,52 @@ var ts; var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; - var context = ""; + var context_2 = ""; if (diagnostic.file) { - var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; - var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var start = diagnostic.start, length_4 = diagnostic.length, file_9 = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file_9, start + length_4), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file_9, file_9.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file_9.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_9.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; var gutterWidth = (lastLine + 1 + "").length; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } for (var i = firstLine; i <= lastLine; i++) { - context += host.getNewLine(); + context_2 += host.getNewLine(); // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context_2 += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); + var lineStart = ts.getPositionOfLineAndCharacter(file_9, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file_9, i + 1, 0) : file_9.text.length; + var lineContent = file_9.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += lineContent + host.getNewLine(); + context_2 += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context_2 += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += ForegroundColorEscapeSequences.Red; + context_2 += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context_2 += ForegroundColorEscapeSequences.Red; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. var lastCharForLine = i === lastLine ? lastLineChar : undefined; - context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + context_2 += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context_2 += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); } else if (i === lastLine) { - context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + context_2 += lineContent.slice(0, lastLineChar).replace(/./g, "~"); } else { // Squiggle the entire line. - context += lineContent.replace(/./g, "~"); + context_2 += lineContent.replace(/./g, "~"); } - context += resetEscapeSequence; + context_2 += resetEscapeSequence; } output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); output += ":"; @@ -76959,7 +78108,7 @@ var ts; output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); - output += context; + output += context_2; } output += host.getNewLine(); } @@ -76996,13 +78145,13 @@ var ts; var resolutions = []; var cache = ts.createMap(); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_56 = names_1[_i]; + var name = names_1[_i]; var result = void 0; - if (cache.has(name_56)) { - result = cache.get(name_56); + if (cache.has(name)) { + result = cache.get(name); } else { - cache.set(name_56, result = loader(name_56, containingFile)); + cache.set(name, result = loader(name, containingFile)); } resolutions.push(result); } @@ -77069,21 +78218,19 @@ var ts; oldOptions.baseUrl !== newOptions.baseUrl || !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); } - /** - * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' - * that represent a compilation unit. - * - * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and - * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. - * - * @param rootNames - A set of root files. - * @param options - The compiler options which should be used. - * @param host - The host interacts with the underlying file system. - * @param oldProgram - Reuses an old program structure. - * @param configFileParsingDiagnostics - error during config file parsing - * @returns A 'Program' object. - */ - function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -77111,6 +78258,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -77120,6 +78268,7 @@ var ts; // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; + var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; @@ -77159,6 +78308,23 @@ var ts; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences = projectReferences ? [] : undefined; + var projectReferenceRedirects = ts.createMap(); + if (projectReferences) { + for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { + var ref = projectReferences_1[_i]; + var parsedRef = parseProjectReferenceConfigFile(ref); + resolvedProjectReferences.push(parsedRef); + if (parsedRef) { + if (parsedRef.commandLine.options.outFile) { + var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*packageId*/ undefined); + } + addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + } + } + } var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -77198,8 +78364,8 @@ var ts; // not part of the new program. if (oldProgram && host.onReleaseOldSourceFile) { var oldSourceFiles = oldProgram.getSourceFiles(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); } @@ -77240,6 +78406,7 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -77255,9 +78422,14 @@ var ts; if (commonSourceDirectory === undefined) { var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { - // If a rootDir is specified and is valid use it as the commonSourceDirectory + // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } + else if (options.composite) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } else { commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } @@ -77295,16 +78467,16 @@ var ts; // We only set `file.resolvedModules` via work from the current function, // so it is defined iff we already called the current function on `file`. // That call happened no later than the creation of the `file` object, - // which per above occured during the current program creation. + // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -77435,6 +78607,34 @@ var ts; if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { return oldProgram.structureIsReused = 0 /* Not */; } + // Check if any referenced project tsconfig files are different + var oldRefs = oldProgram.getProjectReferences(); + if (projectReferences) { + if (!oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + for (var i = 0; i < projectReferences.length; i++) { + var oldRef = oldRefs[i]; + if (oldRef) { + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); + if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { + // Resolved project reference has gone missing or changed + return oldProgram.structureIsReused = 0 /* Not */; + } + } + else { + // A previously-unresolved reference may be resolved now + if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } + } + } + else { + if (oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; @@ -77602,6 +78802,7 @@ var ts; } function getEmitHost(writeFileCallback) { return { + getPrependNodes: getPrependNodes, getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, @@ -77615,6 +78816,32 @@ var ts; isEmitBlocked: isEmitBlocked, }; } + function getProjectReferences() { + if (!resolvedProjectReferences) + return; + return resolvedProjectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!resolvedRefOpts.options.outFile) + continue; + var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); + var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var node = ts.createInputFiles(js, dts); + nodes.push(node); + } + } + return nodes; + } function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } @@ -77685,7 +78912,7 @@ var ts; var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -77769,9 +78996,9 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); - // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || - sourceFile.scriptKind === 5 /* External */ || isCheckJs; + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -78147,7 +79374,13 @@ var ts; var sourceFile = getSourceFile(fileName); if (fail) { if (!sourceFile) { - fail(ts.Diagnostics.File_0_not_found, fileName); + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); @@ -78208,31 +79441,45 @@ var ts; // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { - var file_1 = filesByName.get(path); + var file_10 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + if (file_10 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_10.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(fileName, file_10.fileName, refFile, refPos, refEnd); } // If the file was previously found via a node_modules search, but is now being processed as a root file, // then everything it sucks in may also be marked incorrectly, and needs to be checked again. - if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { - sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (file_10 && sourceFilesFoundSearchingNodeModules.get(file_10.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_10.path, false); if (!options.noResolve) { - processReferencedFiles(file_1, isDefaultLib); - processTypeReferenceDirectives(file_1); + processReferencedFiles(file_10, isDefaultLib); + processTypeReferenceDirectives(file_10); } - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); + modulesWithElidedImports.set(file_10.path, false); + processImportedModules(file_10); } // See if we need to reprocess the imports due to prior skipped imports - else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + else if (file_10 && modulesWithElidedImports.get(file_10.path)) { if (currentNodeModulesDepth < maxNodeModuleJsDepth) { - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); + modulesWithElidedImports.set(file_10.path, false); + processImportedModules(file_10); } } - return file_1; + return file_10; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } } // We haven't looked for this file, do so now and cache result var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { @@ -78263,6 +79510,9 @@ var ts; } } filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; @@ -78293,6 +79543,22 @@ var ts; } return file; } + function getProjectReferenceRedirect(fileName) { + var path = toPath(fileName); + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var normalized = ts.getNormalizedAbsolutePath(fileName, path); + var result; + projectReferenceRedirects.forEach(function (v, k) { + if (result !== undefined) { + return undefined; + } + if (normalized.indexOf(k) === 0) { + result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); + } + }); + return result; + } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); @@ -78302,6 +79568,9 @@ var ts; function processTypeReferenceDirectives(file) { // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; @@ -78381,7 +79650,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -78423,9 +79692,9 @@ var ts; function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); + var file_11 = sourceFiles_2[_i]; + if (!file_11.isDeclarationFile) { + fileNames.push(file_11.fileName); } } return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); @@ -78447,6 +79716,27 @@ var ts; } return allFilesBelongToPath; } + function parseProjectReferenceConfigFile(ref) { + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(host, ref); + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + if (sourceFile === undefined) { + return undefined; + } + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + return { commandLine: commandLine, sourceFile: sourceFile }; + } + function addProjectReferenceRedirects(referencedProject, target) { + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); + target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); + } + function getDeclarationOutputDirectory(proj) { + return proj.options.declarationDir || + proj.options.outDir || + ts.getDirectoryPath(proj.options.configFilePath); + } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !options.strictNullChecks) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); @@ -78476,6 +79766,48 @@ var ts; if (options.paths && options.baseUrl === undefined) { createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + if (projectReferences) { + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; + if (resolvedRefOpts === undefined) { + createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); + continue; + } + if (!resolvedRefOpts.composite) { + createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + if (ref.prepend) { + if (resolvedRefOpts.outFile) { + if (!host.fileExists(resolvedRefOpts.outFile)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + } + } + else { + createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + } + } + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite && rootNames.length < files.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); + var _loop_10 = function (file_12) { + if (normalizedRootNames.every(function (r) { return r !== file_12; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file_12)); + } + }; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var file_12 = sourceFiles_4[_i]; + _loop_10(file_12); + } + } if (options.paths) { for (var key in options.paths) { if (!ts.hasProperty(options.paths, key)) { @@ -78567,6 +79899,11 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified @@ -78679,12 +80016,15 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); } } - function getOptionPathsSyntax() { + function getOptionsSyntaxByName(name) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); if (compilerOptionsObjectLiteralSyntax) { - return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); } - return ts.emptyArray; + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; } function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); @@ -78692,6 +80032,15 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } + function createDiagnosticForReference(index, message, arg0, arg1) { + var referencesSyntax = getProjectReferencesSyntax(); + if (referencesSyntax) { + if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { + return; + } + } + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || @@ -78700,11 +80049,28 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } + function getProjectReferencesSyntax() { + if (_referencesArrayLiteralSyntax === undefined) { + _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword + if (options.configFile) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isArrayLiteralExpression(prop.initializer)) { + _referencesArrayLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _referencesArrayLiteralSyntax; + } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile && options.configFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { var prop = _a[_i]; if (ts.isObjectLiteralExpression(prop.initializer)) { _compilerOptionsObjectLiteralSyntax = prop.initializer; @@ -78723,6 +80089,13 @@ var ts; } return !!props.length; } + function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { + if (arrayLiteral.elements.length <= index) { + // Out-of-bounds + return false; + } + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -78759,6 +80132,27 @@ var ts; } ts.createProgram = createProgram; /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + /** + * Returns the target config filename of a project reference + */ + function resolveProjectReferencePath(host, ref) { + if (!host.fileExists(ref.path)) { + return ts.combinePaths(ref.path, "tsconfig.json"); + } + return ref.path; + } + /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. @@ -78769,6 +80163,7 @@ var ts; switch (extension) { case ".ts" /* Ts */: case ".d.ts" /* Dts */: + case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check // These are always allowed. return undefined; case ".tsx" /* Tsx */: @@ -78969,6 +80364,7 @@ var ts; * Get all the dependencies of the sourceFile */ function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; var compilerOptions = programOfThisState.getCompilerOptions(); // With --out or --outFile all outputs go into single file, all files depend on each other if (compilerOptions.outFile || compilerOptions.out) { @@ -78988,7 +80384,7 @@ var ts; var references = state.referencedMap.get(path); if (references) { var iterator = references.keys(); - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { queue.push(value); } } @@ -78998,7 +80394,6 @@ var ts; var file = programOfThisState.getSourceFileByPath(path); return file ? file.fileName : path; })); - var _b; } BuilderState.getAllDependencies = getAllDependencies; /** @@ -79443,8 +80838,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_1 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -79522,6 +80917,7 @@ var ts; startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, @@ -79630,23 +81026,23 @@ var ts; var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); var seenNamesInFile = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_57 = names_2[_i]; - var resolution = resolutionsInFile.get(name_57); + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated - if (!seenNamesInFile.has(name_57) && + if (!seenNamesInFile.has(name) && allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name_57) && !getResolutionWithResolvedFileName(resolution))) { + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { var existingResolution = resolution; - var resolutionInDirectory = perDirectoryResolution.get(name_57); + var resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { resolution = resolutionInDirectory; } else { - resolution = loader(name_57, containingFile, compilerOptions, resolutionHost); - perDirectoryResolution.set(name_57, resolution); + resolution = loader(name, containingFile, compilerOptions, resolutionHost); + perDirectoryResolution.set(name, resolution); } - resolutionsInFile.set(name_57, resolution); + resolutionsInFile.set(name, resolution); watchFailedLookupLocationOfResolution(resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); @@ -79658,7 +81054,7 @@ var ts; } } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); - seenNamesInFile.set(name_57, true); + seenNamesInFile.set(name, true); resolvedModules.push(getResolutionWithResolvedFileName(resolution)); } // Stop watching and remove the unused name @@ -79694,6 +81090,10 @@ var ts; function resolveModuleNames(moduleNames, containingFile, reusedNames) { return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } @@ -79741,17 +81141,19 @@ var ts; return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } // Use some ancestor of the root directory + var subDirectory; if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { var parentPath = ts.getDirectoryPath(dirPath); if (parentPath === dirPath) { break; } + subDirectory = dirPath.slice(parentPath.length + ts.directorySeparator.length); dirPath = parentPath; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath, subDirectory: subDirectory }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -79771,7 +81173,7 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { // If the failed lookup location path is not one of the supported extensions, // store it in the custom path @@ -79783,7 +81185,7 @@ var ts; setAtRoot = true; } else { - setDirectoryWatcher(dir, dirPath); + setDirectoryWatcher(dir, dirPath, subDirectory); } } } @@ -79791,13 +81193,19 @@ var ts; setDirectoryWatcher(rootDir, rootPath); } } - function setDirectoryWatcher(dir, dirPath) { + function setDirectoryWatcher(dir, dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { dirWatcher.refCount++; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }; + directoryWatchesOfFailedLookups.set(dirPath, dirWatcher); + } + if (subDirectory) { + var subDirectoryMap = dirWatcher.subDirectoryMap || (dirWatcher.subDirectoryMap = ts.createMap()); + var existing = subDirectoryMap.get(subDirectory) || 0; + subDirectoryMap.set(subDirectory, existing + 1); } } function stopWatchFailedLookupLocationOfResolution(resolution) { @@ -79813,7 +81221,7 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { @@ -79829,7 +81237,7 @@ var ts; removeAtRoot = true; } else { - removeDirectoryWatcher(dirPath); + removeDirectoryWatcher(dirPath, subDirectory); } } } @@ -79837,22 +81245,40 @@ var ts; removeDirectoryWatcher(rootPath); } } - function removeDirectoryWatcher(dirPath) { + function removeDirectoryWatcher(dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (subDirectory) { + var existing = dirWatcher.subDirectoryMap.get(subDirectory); + if (existing === 1) { + dirWatcher.subDirectoryMap.delete(subDirectory); + } + else { + dirWatcher.subDirectoryMap.set(subDirectory, existing - 1); + } + } // Do not close the watcher yet since it might be needed by other failed lookup locations. dirWatcher.refCount--; } + function inWatchedSubdirectory(dirPath, fileOrDirectoryPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (!dirWatcher || !dirWatcher.subDirectoryMap) + return false; + return ts.forEachKey(dirWatcher.subDirectoryMap, function (subDirectory) { + var fullSubDirectory = dirPath + "/" + subDirectory; + return fullSubDirectory === fileOrDirectoryPath || isInDirectoryPath(fullSubDirectory, fileOrDirectoryPath); + }); + } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // If the files are added to project root or node_modules directory, always run through the invalidation process // Otherwise run through invalidation only if adding to the immediate directory if (!allFilesHaveInvalidatedResolution && - dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + (dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath || inWatchedSubdirectory(dirPath, fileOrDirectoryPath))) { if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { resolutionHost.onInvalidatedResolution(); } @@ -79976,7 +81402,7 @@ var ts; return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // For now just recompile @@ -80112,34 +81538,11 @@ var ts; function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; - var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - /** - * Reads the config file, reports errors if any and exits if the config file cannot be found - */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - var result = ts.parseJsonText(configFileName, configFileText); - var cwd = host.getCurrentDirectory(); - return ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); - } - ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ @@ -80221,12 +81624,12 @@ var ts; watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, setTimeout: system.setTimeout ? (function (callback, ms) { + var _a; var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - var _a; }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, trace: function (s) { return system.write(s); }, @@ -80986,6 +82389,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, { name: "removeComments", type: "boolean", @@ -81246,6 +82656,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, { name: "listFiles", type: "boolean", @@ -81539,11 +82955,13 @@ var ts; function parseCommandLine(commandLine, readFile) { var options = {}; var fileNames = []; + var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, + projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -81656,6 +83074,29 @@ var ts; } return optionNameMap.get(optionName); } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -81703,55 +83144,67 @@ var ts; var _tsconfigRootOptions; function getTsconfigRootOptionsMap() { if (_tsconfigRootOptions === undefined) { - _tsconfigRootOptions = commandLineOptionsToMap([ - { - name: "compilerOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 - }, - { - name: "typingOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "typeAcquisition", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "extends", - type: "string" - }, - { - name: "files", - type: "list", - element: { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { name: "files", - type: "string" - } - }, - { - name: "include", - type: "list", - element: { + type: "list", + element: { + name: "files", + type: "string" + } + }, + { name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { + type: "list", + element: { + name: "include", + type: "string" + } + }, + { name: "exclude", - type: "string" - } - }, - ts.compileOnSaveCommandLineOption - ]); + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; } return _tsconfigRootOptions; } @@ -81759,20 +83212,25 @@ var ts; * Convert the json syntax tree into the json value */ function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } ts.convertToObject = convertToObject; /** - * Convert the json syntax tree into the json value + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined */ - function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.jsonObject) { - return {}; + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, - /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined); function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { - var result = {}; + var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; if (element.kind !== 269 /* PropertyAssignment */) { @@ -81792,11 +83250,13 @@ var ts; } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { - result[keyText] = value; + if (returnValue) { + result[keyText] = value; + } // Notify key value set, if user asked for it if (jsonConversionNotifier && // Current callbacks are only on known parent option or if we are setting values in the root - (parentOption || knownOptions === knownRootOptions)) { + (parentOption || isRootOptionMap(knownOptions))) { var isValidOptionValue = isCompilerOptionsValue(option, value); if (parentOption) { if (isValidOptionValue) { @@ -81804,7 +83264,7 @@ var ts; jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); } } - else if (knownOptions === knownRootOptions) { + else if (isRootOptionMap(knownOptions)) { if (isValidOptionValue) { // Notify about the valid root key value being set jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); @@ -81820,7 +83280,7 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -81895,6 +83355,7 @@ var ts; return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } + ts.convertToObjectWorker = convertToObjectWorker; function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : @@ -81944,36 +83405,36 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_9 = function (name_58) { - if (ts.hasProperty(options, name_58)) { + var _loop_11 = function (name) { + if (ts.hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name_58) && optionsNameMap.get(name_58).category === ts.Diagnostics.Command_line_Options) { + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; } - var value = options[name_58]; - var optionDefinition = optionsNameMap.get(name_58.toLowerCase()); + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); if (!customTypeMap_1) { // There is no map associated with this compiler option then use the value as-is // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name_58, value); + result.set(name, value); } else { if (optionDefinition.type === "list") { - result.set(name_58, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); } else { // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name_58, getNameOfCompilerOptionValue(value, customTypeMap_1)); + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); } } } } }; - for (var name_58 in options) { - _loop_9(name_58); + for (var name in options) { + _loop_11(name); } return result; } @@ -82123,12 +83584,13 @@ var ts; var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); - options.configFilePath = configFileName; + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; return { options: options, fileNames: fileNames, + projectReferences: projectReferences, typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), raw: raw, errors: errors, @@ -82167,19 +83629,43 @@ var ts; createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } - else { - var outDir = raw.compilerOptions && raw.compilerOptions.outDir; - if (outDir) { - excludeSpecs = [outDir]; + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); } } if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + var references = []; + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + references.push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + result.projectReferences = references; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } return result; } function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { @@ -82297,7 +83783,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -82332,6 +83818,7 @@ var ts; return extendedConfigPath; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -82360,7 +83847,6 @@ var ts; mapPropertiesInRawIfNotUndefined("files"); } return extendedConfig; - var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { @@ -82385,7 +83871,7 @@ var ts; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function getDefaultCompilerOptions(configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {}; return options; @@ -82393,10 +83879,13 @@ var ts; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -82557,7 +84046,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -82591,37 +84080,41 @@ var ts; if (filesSpecs) { for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { var fileName = filesSpecs_1[_i]; - var file = ts.getNormalizedAbsolutePath(fileName, basePath); - literalFileMap.set(keyMapper(file), file); + var file_13 = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file_13), file_13); } } if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var file_14 = _b[_a]; // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // // This handles cases where we may encounter both .ts and // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. - if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + if (hasFileWithHigherPriorityExtension(file_14, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the // "include" array. If there is a lower priority extension in the // same directory, we should remove it. - removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); - var key = keyMapper(file); + removeWildcardFilesWithLowerPriorityExtension(file_14, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file_14); if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { - wildcardFileMap.set(key, file); + wildcardFileMap.set(key, file_14); } } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { + return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); + }); return { fileNames: literalFiles.concat(wildcardFiles), + projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -82636,20 +84129,10 @@ var ts; return diag === undefined; }); function createDiagnostic(message, spec) { - if (jsonSourceFile && jsonSourceFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { - var property = _a[_i]; - if (ts.isArrayLiteralExpression(property.initializer)) { - for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (ts.isStringLiteral(element) && element.text === spec) { - return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); - } - } - } - } - } - return ts.createCompilerDiagnostic(message, spec); + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); } } function specToDiagnostic(spec, allowTrailingRecursion) { @@ -82682,8 +84165,8 @@ var ts; if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { - var file = include_1[_i]; - var spec = ts.normalizePath(ts.combinePaths(path, file)); + var file_15 = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file_15)); if (excludeRegex && excludeRegex.test(spec)) { continue; } @@ -82877,6 +84360,17 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + /** Single or multi-line comments */ + OutliningSpanKind["Comment"] = "comment"; + /** Sections marked by '// #region' and '// #endregion' comments */ + OutliningSpanKind["Region"] = "region"; + /** Declarations and expressions */ + OutliningSpanKind["Code"] = "code"; + /** Contiguous blocks of import declarations */ + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); var OutputFileType; (function (OutputFileType) { OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; @@ -82972,6 +84466,8 @@ var ts; * */ ScriptElementKind["jsxAttribute"] = "JSX attribute"; + /** String literal */ + ScriptElementKind["string"] = "string"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -83077,7 +84573,7 @@ var ts; case 236 /* TypeAliasDeclaration */: case 165 /* TypeLiteral */: return 2 /* Type */; - case 292 /* JSDocTypedefTag */: + case 296 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; case 272 /* EnumMember */: @@ -83131,6 +84627,10 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName return 2 /* Type */; } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } else { return 1 /* Value */; } @@ -83193,6 +84693,8 @@ var ts; switch (node.parent.kind) { case 161 /* TypeReference */: return true; + case 178 /* ImportType */: + return !node.parent.isTypeOf; case 206 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } @@ -83280,7 +84782,7 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 292 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(node)) { // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. // Then we get parent again in the loop. @@ -83318,7 +84820,10 @@ var ts; case 204 /* ClassExpression */: return "class" /* classElement */; case 235 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 236 /* TypeAliasDeclaration */: return "type" /* typeElement */; + case 236 /* TypeAliasDeclaration */: + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + return "type" /* typeElement */; case 237 /* EnumDeclaration */: return "enum" /* enumElement */; case 231 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); @@ -83349,8 +84854,6 @@ var ts; case 251 /* ExportSpecifier */: case 245 /* NamespaceImport */: return "alias" /* alias */; - case 292 /* JSDocTypedefTag */: - return "type" /* typeElement */; case 199 /* BinaryExpression */: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; @@ -83412,6 +84915,10 @@ var ts; return startEndContainsRange(r1.pos, r1.end, r2); } ts.rangeContainsRange = rangeContainsRange; + function rangeContainsPosition(r, pos) { + return r.pos <= pos && pos <= r.end; + } + ts.rangeContainsPosition = rangeContainsPosition; function startEndContainsRange(start, end, range) { return start <= range.pos && end >= range.end; } @@ -83678,7 +85185,7 @@ var ts; return findPrecedingToken(position, file); } ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { + function findNextToken(previousToken, parent, sourceFile) { return find(parent); function find(n) { if (ts.isToken(n) && n.pos === previousToken.end) { @@ -83693,7 +85200,7 @@ var ts; (child.pos <= previousToken.pos && child.end > previousToken.end) || // previous token ends exactly at the beginning of child (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { + if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) { return find(child); } } @@ -83724,11 +85231,11 @@ var ts; if (position < child.end) { var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || // cursor in the leading trivia - !nodeHasTokens(child) || + !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } else { @@ -83743,7 +85250,7 @@ var ts; // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } } @@ -83757,19 +85264,19 @@ var ts; return n; } var children = n.getChildren(sourceFile); - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } /** * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. */ - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { var child = children[i]; if (isWhiteSpaceOnlyJsxText(child)) { ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); } - else if (nodeHasTokens(children[i])) { + else if (nodeHasTokens(children[i], sourceFile)) { return children[i]; } } @@ -83881,22 +85388,22 @@ var ts; remainingLessThanTokens++; break; case 18 /* CloseBraceToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); if (!token) return false; break; case 20 /* CloseParenToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); if (!token) return false; break; case 22 /* CloseBracketToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); if (!token) return false; @@ -83950,10 +85457,10 @@ var ts; } } ts.hasDocComment = hasDocComment; - function nodeHasTokens(n) { + function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth() !== 0; + return n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.getCombinedModifierFlags(node); @@ -84050,11 +85557,6 @@ var ts; return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); @@ -84077,6 +85579,10 @@ var ts; return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createTextRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { return createTextChange(ts.createTextSpan(start, length), newText); } @@ -84109,7 +85615,6 @@ var ts; return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; - /** Returns `true` the first time it encounters a node and `false` afterwards. */ function nodeSeenTracker() { var seen = []; return function (node) { @@ -84157,6 +85662,63 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + } + ts.makeImport = makeImport; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default" /* Default */) { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { + // See GH#16922 + ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); + return propSymbol.target; + } + return propSymbol; + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -84489,20 +86051,20 @@ var ts; * user was before extracting it. */ /* @internal */ - function getRenameLocation(edits, renameFilename, name, isDeclaredBeforeUse) { + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { var delta = 0; var lastPos = -1; for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; ts.Debug.assert(fileName === renameFilename); - for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { - var change = textChanges_2[_b]; + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; var span = change.span, newText = change.newText; var index = newText.indexOf(name); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. - if (!isDeclaredBeforeUse) { + if (!preferLastLocation) { return lastPos; } } @@ -84510,7 +86072,7 @@ var ts; } } // If the declaration comes first, return the position of the last occurrence. - ts.Debug.assert(isDeclaredBeforeUse); + ts.Debug.assert(preferLastLocation); ts.Debug.assert(lastPos >= 0); return lastPos; } @@ -85158,20 +86720,22 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 288 /* JSDocParameterTag */: + case 292 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); + pos = tag.end; break; - case 290 /* JSDocTypeTag */: + case 294 /* JSDocTypeTag */: processElement(tag.typeExpression); + pos = tag.end; break; - case 289 /* JSDocReturnTag */: + case 293 /* JSDocReturnTag */: processElement(tag.typeExpression); + pos = tag.end; break; } - pos = tag.end; } } if (pos !== docComment.end) { @@ -85413,7 +86977,7 @@ var ts; var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = ts.getSupportedExtensions(compilerOptions); + var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); } @@ -85426,6 +86990,12 @@ var ts; return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json" /* Json */) : + extensions; + } /** * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option @@ -85464,13 +87034,16 @@ var ts; * Remove the basename from the path. Note that we don't use the basename to filter completions; * the client is responsible for refining completions. */ - fragment = ts.getDirectoryPath(fragment); + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } if (fragment === "") { fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); - var baseDirectory = ts.getDirectoryPath(absolutePath); + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (tryDirectoryExists(host, baseDirectory)) { // Enumerate the available files if possible @@ -85489,7 +87062,7 @@ var ts; if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; } - var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } @@ -85502,8 +87075,8 @@ var ts; var directories = tryGetDirectories(host, baseDirectory); if (directories) { for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var directory = directories_1[_a]; - var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + var directory_2 = directories_1[_a]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory_2)); if (directoryName !== "@types") { result.push(nameAndKind(directoryName, "directory" /* directory */)); } @@ -85522,7 +87095,7 @@ var ts; function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); @@ -85530,20 +87103,20 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_10 = function (name_59, kind) { + var _loop_12 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name_59; })) { - result.push(nameAndKind(name_59, kind)); + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name_59 = _b.name, kind = _b.kind; - _loop_10(name_59, kind); + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_12(name, kind); } } } } - var fragmentDirectory = containsSlash(fragment) ? ts.getDirectoryPath(fragment) : undefined; + var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { var ambientName = _d[_c]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); @@ -85554,7 +87127,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_11 = function (moduleName) { + var _loop_13 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); @@ -85562,7 +87135,7 @@ var ts; }; for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { var moduleName = _f[_e]; - _loop_11(moduleName); + _loop_13(moduleName); } } if (!foundGlobal) { @@ -85598,12 +87171,13 @@ var ts; } // The prefix has two effective parts: the directory path and the base component after the filepath that is not a // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); var fragmentHasPath = containsSlash(fragment); + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); @@ -85764,15 +87338,6 @@ var ts; } return false; } - function normalizeAndPreserveTrailingSlash(path) { - if (ts.normalizeSlashes(path) === "./") { - // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case. - // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning. - return ""; - } - var norm = ts.normalizePath(path); - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; - } /** * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment @@ -85892,7 +87457,7 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); }); + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: @@ -86062,13 +87627,13 @@ var ts; if (!entry) { continue; } - var name_60 = entry.name; - if (uniques.has(name_60)) { + var name = entry.name; + if (uniques.has(name)) { continue; } // Latter case tests whether this is a global variable. if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { - uniques.set(name_60, true); + uniques.set(name, true); } entries.push(entry); } @@ -86090,11 +87655,11 @@ var ts; break; } if (ts.isLabeledStatement(current)) { - var name_61 = current.label.text; - if (!uniques.has(name_61)) { - uniques.set(name_61, true); + var name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); entries.push({ - name: name_61, + name: name, kindModifiers: "" /* none */, kind: "label" /* label */, sortText: "0" @@ -86273,9 +87838,9 @@ var ts; } } case "symbol": { - var symbol = symbolCompletion.symbol, location_3 = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; - return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location_3, cancellationToken, codeActions, sourceDisplay); + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); } case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. @@ -86459,11 +88024,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 275 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 277 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 293 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 297 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -86509,19 +88074,19 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_21 = contextToken.parent; + var parent = contextToken.parent; if (contextToken.kind === 23 /* DotToken */) { isRightOfDot = true; - switch (parent_21.kind) { + switch (parent.kind) { case 184 /* PropertyAccessExpression */: - propertyAccessToConvert = parent_21; + propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; break; case 145 /* QualifiedName */: - node = parent_21.left; + node = parent.left; break; case 178 /* ImportType */: - node = parent_21; + node = parent; break; default: // There is nothing that precedes the dot, so this likely just a stray character @@ -86533,9 +88098,9 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent_21 && parent_21.kind === 184 /* PropertyAccessExpression */) { - contextToken = parent_21; - parent_21 = parent_21.parent; + if (parent && parent.kind === 184 /* PropertyAccessExpression */) { + contextToken = parent; + parent = parent.parent; } // Fix location if (currentToken.parent === location) { @@ -86552,7 +88117,7 @@ var ts; break; } } - switch (parent_21.kind) { + switch (parent.kind) { case 257 /* JsxClosingElement */: if (contextToken.kind === 41 /* SlashToken */) { isStartingCloseTag = true; @@ -86560,7 +88125,7 @@ var ts; } break; case 199 /* BinaryExpression */: - if (!(parent_21.left.flags & 32768 /* ThisNodeHasError */)) { + if (!(parent.left.flags & 32768 /* ThisNodeHasError */)) { // It has a left-hand side, so we're not in an opening JSX tag. break; } @@ -86580,7 +88145,7 @@ var ts; break; case 71 /* Identifier */: // For `
- return parent_23.parent.parent; + return parent.parent.parent; } break; // The context token is the closing } or " of an attribute, which means // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent_23 && ((parent_23.kind === 261 /* JsxAttribute */) || (parent_23.kind === 263 /* JsxSpreadAttribute */))) { + if (parent && ((parent.kind === 261 /* JsxAttribute */) || (parent.kind === 263 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes // properties: NodeArray - return parent_23.parent.parent; + return parent.parent.parent; } break; case 18 /* CloseBraceToken */: - if (parent_23 && - parent_23.kind === 264 /* JsxExpression */ && - parent_23.parent && parent_23.parent.kind === 261 /* JsxAttribute */) { + if (parent && + parent.kind === 264 /* JsxExpression */ && + parent.parent && parent.parent.kind === 261 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes // properties: NodeArray // each JsxAttribute can have initializer as JsxExpression - return parent_23.parent.parent.parent; + return parent.parent.parent.parent; } - if (parent_23 && parent_23.kind === 263 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 263 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes // properties: NodeArray - return parent_23.parent.parent; + return parent.parent.parent; } break; } @@ -87454,8 +89015,8 @@ var ts; // TODO: Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - var name_62 = ts.getNameOfDeclaration(m); - existingName = ts.isPropertyNameLiteral(name_62) ? ts.getEscapedTextOfIdentifierOrLiteral(name_62) : undefined; + var name = ts.getNameOfDeclaration(m); + existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } existingMemberNames.set(existingName, true); } @@ -87670,7 +89231,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 294 /* SyntaxList */: + case 298 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -87707,6 +89268,9 @@ var ts; } function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { + case ".": + case "@": + return true; case '"': case "'": case "`": @@ -87715,8 +89279,12 @@ var ts; case "<": // Opening JSX tag return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */; + case "/": + return ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); default: - return ts.Debug.fail(triggerCharacter); + return ts.Debug.assertNever(triggerCharacter); } } function isStringLiteralOrTemplate(node) { @@ -87811,6 +89379,10 @@ var ts; case 125 /* GetKeyword */: case 136 /* SetKeyword */: return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]); + case 121 /* AwaitKeyword */: + return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); + case 120 /* AsyncKeyword */: + return highlightSpans(getAsyncAndAwaitOccurrences(node)); default: return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) @@ -87851,16 +89423,16 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_24 = child.parent; - if (ts.isFunctionBlock(parent_24) || parent_24.kind === 273 /* SourceFile */) { - return parent_24; + var parent = child.parent; + if (ts.isFunctionBlock(parent) || parent.kind === 273 /* SourceFile */) { + return parent; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. - if (ts.isTryStatement(parent_24) && parent_24.tryBlock === child && parent_24.catchClause) { + if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) { return child; } - child = parent_24; + child = parent; } return undefined; } @@ -88058,6 +89630,29 @@ var ts; }); return keywords; } + function getAsyncAndAwaitOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + if (func.modifiers) { + func.modifiers.forEach(function (modifier) { + pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */); + }); + } + ts.forEachChild(func, aggregate); + return keywords; + function aggregate(node) { + if (ts.isAwaitExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */); + } + // Do not cross function boundaries. + if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) { + ts.forEachChild(node, aggregate); + } + } + } function getIfElseOccurrences(ifStatement, sourceFile) { var keywords = getIfElseKeywords(ifStatement, sourceFile); var result = []; @@ -88178,9 +89773,10 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); entry = { sourceFile: sourceFile, languageServiceRefCount: 1, @@ -88297,11 +89893,11 @@ var ts; switch (direct.kind) { case 186 /* CallExpression */: if (!isAvailableThroughGlobal) { - var parent_25 = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent_25.kind === 231 /* VariableDeclaration */) { - var name_63 = parent_25.name; - if (name_63.kind === 71 /* Identifier */) { - directImports.push(name_63); + var parent = direct.parent; + if (exportKind === 2 /* ExportEquals */ && parent.kind === 231 /* VariableDeclaration */) { + var name = parent.name; + if (name.kind === 71 /* Identifier */) { + directImports.push(name); break; } } @@ -88309,6 +89905,8 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; + case 71 /* Identifier */: // for 'const x = require("y"); + break; // TODO: GH#23879 case 242 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */)); break; @@ -88338,6 +89936,11 @@ var ts; directImports.push(direct); } break; + case 178 /* ImportType */: + directImports.push(direct); + break; + default: + ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); } } } @@ -88415,6 +90018,14 @@ var ts; return; } if (decl.kind === 178 /* ImportType */) { + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); + } return; } // Ignore if there's a grammar error @@ -88439,12 +90050,12 @@ var ts; } else { // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals - var name_64 = importClause.name; + var name = importClause.name; // If a default import has the same name as the default export, allow to rename it. // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. - if (name_64 && (!isForRename || name_64.escapedText === symbolName(exportSymbol))) { - var defaultImportAlias = checker.getSymbolAtLocation(name_64); - addSearch(name_64, defaultImportAlias); + if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); } // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 1 /* Default */) { @@ -88469,8 +90080,8 @@ var ts; } for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var element = _a[_i]; - var name_65 = element.name, propertyName = element.propertyName; - if (!isNameMatch((propertyName || name_65).escapedText)) { + var name = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name).escapedText)) { continue; } if (propertyName) { @@ -88478,16 +90089,16 @@ var ts; singleReferences.push(propertyName); // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`. // But do rename `foo` in ` { default as foo }` if that's the original export name. - if (!isForRename || name_65.escapedText === exportSymbol.escapedName) { + if (!isForRename || name.escapedText === exportSymbol.escapedName) { // Search locally for `bar`. - addSearch(name_65, checker.getSymbolAtLocation(name_65)); + addSearch(name, checker.getSymbolAtLocation(name)); } } else { var localSymbol = element.kind === 251 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. - : checker.getSymbolAtLocation(name_65); - addSearch(name_65, localSymbol); + : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); } } } @@ -88500,24 +90111,18 @@ var ts; function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { - if (statement.kind !== 249 /* ExportDeclaration */) + if (!ts.isExportDeclaration(statement)) return; - var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier; - if (moduleSpecifier || !exportClause) - return; - for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) { - var element = _b[_i]; - if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) { - return true; - } - } + var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; + return !moduleSpecifier && exportClause && + exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; }); }); } function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var referencingFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var referencingFile = sourceFiles_5[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 273 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -88547,8 +90152,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -88653,6 +90258,9 @@ var ts; else if (ts.isBinaryExpression(parent.parent)) { return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); } + else if (ts.isJSDocTypedefTag(parent)) { + return exportInfo(symbol, 0 /* Named */); + } } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. @@ -88697,7 +90305,7 @@ var ts; // If the import has a different name than the export, do not continue searching. // If `importedName` is undefined, do continue searching as the export is anonymous. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) - var importedName = symbolName(importedSymbol); + var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } @@ -88764,15 +90372,6 @@ var ts; return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; } FindAllReferences.getExportInfo = getExportInfo; - function symbolName(symbol) { - if (symbol.escapedName !== "default" /* Default */) { - return symbol.escapedName; - } - return ts.forEach(symbol.declarations, function (decl) { - var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ && name.escapedText; - }); - } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. @@ -88847,9 +90446,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 270 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -88882,8 +90481,8 @@ var ts; case "symbol": { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_66 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_66, kind: kind_1, displayParts: displayParts_1 }; + var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_3 = def.node; @@ -88891,13 +90490,13 @@ var ts; } case "keyword": { var node_4 = def.node; - var name_67 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_67, kind: "keyword" /* keyword */, displayParts: [{ text: name_67, kind: "keyword" /* keyword */ }] }; + var name_4 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } case "this": { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { @@ -89010,7 +90609,7 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -89025,32 +90624,36 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } - if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { - return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet); + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + node = undefined; } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function isModuleReferenceLocation(node) { - if (!ts.isStringLiteralLike(node)) { - return false; - } - switch (node.parent.kind) { - case 238 /* ModuleDeclaration */: - case 253 /* ExternalModuleReference */: - case 243 /* ImportDeclaration */: - case 249 /* ExportDeclaration */: - return true; - case 186 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent); - default: - return false; - } + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile); } - function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) { + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); - var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. return { type: "node", node: reference.literal }; } else { @@ -89073,10 +90676,11 @@ var ts; } break; default: + // This may be merged with something. ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; + return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -89104,17 +90708,17 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; - var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); - if (node.kind === 79 /* DefaultKeyword */) { + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + if (node && node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -89160,7 +90764,6 @@ var ts; return ts.firstDefined(symbol.declarations, function (decl) { if (!decl.parent) { // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. - ts.Debug.assert(decl.kind === 273 /* SourceFile */); ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol)); } return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) @@ -89234,7 +90837,7 @@ var ts; // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** @@ -89278,10 +90881,8 @@ var ts; var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; - // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - if (!(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) { + if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); - } } } // For each import, find all references to that import in its source file. @@ -89310,6 +90911,17 @@ var ts; } } } + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -89333,22 +90945,14 @@ var ts; var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */); if (bindingElement && bindingElement.parent.kind === 179 /* ObjectBindingPattern */ && + ts.isIdentifier(bindingElement.name) && !bindingElement.propertyName) { return bindingElement; } } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - if (!bindingElement) - return undefined; - var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { - // See GH#16922 - ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); - return propSymbol.target; - } - return propSymbol; + return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); } /** * Determines the smallest scope in which a symbol may have named references. @@ -89519,6 +91123,9 @@ var ts; getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } + function hasMatchingMeaning(referenceLocation, state) { + return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (!isValidReferencePosition(referenceLocation, search.text)) { @@ -89534,9 +91141,8 @@ var ts; } return; } - if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) { + if (!hasMatchingMeaning(referenceLocation, state)) return; - } var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); if (!referenceSymbol) { return; @@ -90197,7 +91803,9 @@ var ts; var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. - return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) + return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) || + // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); }) ? [sigInfo] : [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node)); } @@ -90252,14 +91860,14 @@ var ts; function getReferenceAtPosition(sourceFile, position, program) { var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { - var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); - return file && { fileName: referencePath.fileName, file: file }; + var file_16 = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file_16 && { fileName: referencePath.fileName, file: file_16 }; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - var file = reference && program.getSourceFile(reference.resolvedFileName); - return file && { fileName: typeReferenceDirective.fileName, file: file }; + var file_17 = reference && program.getSourceFile(reference.resolvedFileName); + return file_17 && { fileName: typeReferenceDirective.fileName, file: file_17 }; } return undefined; } @@ -90431,6 +92039,7 @@ var ts; "author", "argument", "borrows", + "callback", "class", "constant", "constructor", @@ -90495,10 +92104,12 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 293 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: + case 297 /* JSDocPropertyTag */: return [declaration]; - case 292 /* JSDocTypedefTag */: - return [declaration.parent]; + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); } @@ -90518,17 +92129,18 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 286 /* JSDocAugmentsTag */: + case 289 /* JSDocAugmentsTag */: return withNode(tag.class); - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 290 /* JSDocTypeTag */: + case 294 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 292 /* JSDocTypedefTag */: - case 293 /* JSDocPropertyTag */: - case 288 /* JSDocParameterTag */: - var name_68 = tag.name; - return name_68 ? withNode(name_68) : comment; + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + case 297 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: + var name = tag.name; + return name ? withNode(name) : comment; default: return comment; } @@ -90851,12 +92463,42 @@ var ts; JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ JsTyping.nodeCoreModuleList = [ - "buffer", "querystring", "events", "http", "cluster", - "zlib", "os", "https", "punycode", "repl", "readline", - "vm", "child_process", "url", "dns", "net", - "dgram", "fs", "path", "string_decoder", "tls", - "crypto", "stream", "util", "assert", "tty", "domain", - "constants", "process", "v8", "timers", "console" + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" ]; /* @internal */ JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); @@ -90915,8 +92557,8 @@ var ts; getTypingNamesFromSourceFileNames(fileNames); // add typings for unresolved imports if (unresolvedImports) { - var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); - addInferredTypings(module, "Inferred typings from unresolved imports"); + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); } // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach(function (typing, name) { @@ -91013,8 +92655,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -91114,7 +92756,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_12 = function (sourceFile) { + var _loop_14 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -91124,9 +92766,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; - _loop_12(sourceFile); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + _loop_14(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -91425,9 +93067,9 @@ var ts; break; case 181 /* BindingElement */: case 231 /* VariableDeclaration */: - var _d = node, name_69 = _d.name, initializer = _d.initializer; - if (ts.isBindingPattern(name_69)) { - addChildrenRecursively(name_69); + var _d = node, name = _d.name, initializer = _d.initializer; + if (ts.isBindingPattern(name)) { + addChildrenRecursively(name); } else if (initializer && isFunctionOrClassExpression(initializer)) { if (initializer.name) { @@ -91503,7 +93145,7 @@ var ts; if (ts.hasJSDocNodes(node)) { ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 292 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(tag)) { addLeafNode(tag); } }); @@ -91578,6 +93220,7 @@ var ts; } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { + var _a; target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); if (source.additionalNodes) { @@ -91588,7 +93231,6 @@ var ts; mergeChildren(target.children); sortChildren(target.children); } - var _a; } /** Recursively ensure that each NavNode's children are in sorted order. */ function sortChildren(children) { @@ -91616,8 +93258,6 @@ var ts; case 192 /* ArrowFunction */: case 204 /* ClassExpression */: return getFunctionOrClassName(node); - case 292 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return undefined; } @@ -91659,29 +93299,10 @@ var ts; return "()"; case 159 /* IndexSignature */: return "[]"; - case 292 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return ""; } } - function getJSDocTypedefTagName(node) { - if (node.name) { - return node.name.text; - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 213 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71 /* Identifier */) { - return nameIdentifier.text; - } - } - } - return ""; - } - } /** Flattens the NavNode tree to a list, keeping only the top-level items. */ function topLevelItems(root) { var topLevel = []; @@ -91707,7 +93328,8 @@ var ts; case 238 /* ModuleDeclaration */: case 273 /* SourceFile */: case 236 /* TypeAliasDeclaration */: - case 292 /* JSDocTypedefTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: return true; case 154 /* Constructor */: case 153 /* MethodDeclaration */: @@ -91870,17 +93492,23 @@ var ts; */ function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(topLevelImportDecls); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; var ambientModuleBody = getModuleBlock(ambientModule); var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(ambientModuleImportDecls); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); - function organizeImportsWorker(oldImportDecls) { + function organizeImportsWorker(oldImportDecls, coalesce) { if (ts.length(oldImportDecls) === 0) { return; } @@ -91894,7 +93522,7 @@ var ts; var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + ? coalesce(importGroup) : importGroup; }); // Delete or replace the first import. @@ -91936,10 +93564,10 @@ var ts; usedImports.push(importDecl); continue; } - var name_70 = importClause.name, namedBindings = importClause.namedBindings; + var name = importClause.name, namedBindings = importClause.namedBindings; // Default import - if (name_70 && !isDeclarationUsed(name_70)) { - name_70 = undefined; + if (name && !isDeclarationUsed(name)) { + name = undefined; } if (namedBindings) { if (ts.isNamespaceImport(namedBindings)) { @@ -91958,8 +93586,8 @@ var ts; } } } - if (name_70 || namedBindings) { - usedImports.push(updateImportDeclarationAndClause(importDecl, name_70, namedBindings)); + if (name || namedBindings) { + usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); } } return usedImports; @@ -91969,7 +93597,9 @@ var ts; } } function getExternalModuleName(specifier) { - return ts.isStringLiteralLike(specifier) ? specifier.text : undefined; + return specifier !== undefined && ts.isStringLiteralLike(specifier) + ? specifier.text + : undefined; } /* @internal */ // Internal for testing /** @@ -92015,15 +93645,14 @@ var ts; } } newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); - var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { - return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || - compareIdentifiers(s1.name, s2.name); - }); + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); @@ -92049,8 +93678,8 @@ var ts; importWithoutClause = importWithoutClause || importDeclaration; continue; } - var _a = importDeclaration.importClause, name_71 = _a.name, namedBindings = _a.namedBindings; - if (name_71) { + var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings; + if (name) { defaultImports.push(importDeclaration); } if (namedBindings) { @@ -92069,23 +93698,77 @@ var ts; namedImports: namedImports, }; } - function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); - } } OrganizeImports.coalesceImports = coalesceImports; + /* @internal */ // Internal for testing + /** + * @param exportGroup a list of ExportDeclarations, all with the same module name. + */ + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + /* + * Returns entire export declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + */ + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + // Only the first such export is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); + } /* internal */ // Exported for testing function compareModuleSpecifiers(m1, m2) { var name1 = getExternalModuleName(m1); var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); /* @internal */ @@ -92095,7 +93778,7 @@ var ts; var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) { + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); if (newPath !== undefined) { @@ -92107,25 +93790,16 @@ var ts; } ts.getEditsForFileRename = getEditsForFileRename; function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var cfg = program.getCompilerOptions().configFile; - if (!cfg) - return; - var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath); + var configFile = program.getCompilerOptions().configFile; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); if (oldFile) { - changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath); + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); } } - function getFilesEntry(cfg, fileName) { - var filesProp = ts.find(cfg.properties, function (prop) { - return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; - }); - var files = filesProp && filesProp.initializer; - return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined; - } function isRef(toUpdate) { return "fileName" in toUpdate; } - function getImportsToUpdate(program, oldFilePath) { + function getImportsToUpdate(program, oldFilePath, host) { var checker = program.getTypeChecker(); var result = []; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { @@ -92141,8 +93815,10 @@ var ts; // If it resolved to something already, ignore. if (checker.getSymbolAtLocation(importStringLiteral)) continue; - var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (ts.contains(resolved.failedLookupLocations, oldFilePath)) { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); } } @@ -92151,11 +93827,11 @@ var ts; } function getPathUpdater(oldFilePath, newFilePath, host) { // Get the relative path from old to new location, and append it on to the end of imports and normalize. - var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); return function (oldPath) { if (!ts.pathIsRelative(oldPath)) return; - return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); }; } function createStringRange(node, sourceFile) { @@ -92176,7 +93852,27 @@ var ts; OutliningElementsCollector.collectElements = collectElements; function addNodeOutliningSpans(sourceFile, cancellationToken, out) { var depthRemaining = 40; - sourceFile.forEachChild(function walk(n) { + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + } + } + function visitNonImportNode(n) { if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); @@ -92189,17 +93885,17 @@ var ts; depthRemaining--; if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { // Consider an 'else if' to be on the same depth as the 'if'. - walk(n.expression); - walk(n.thenStatement); + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); depthRemaining++; - walk(n.elseStatement); + visitNonImportNode(n.elseStatement); depthRemaining--; } else { - n.forEachChild(walk); + n.forEachChild(visitNonImportNode); } depthRemaining++; - }); + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -92214,7 +93910,7 @@ var ts; } if (!result[1]) { var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); - regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region")); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region")); } else { var region = regions.pop(); @@ -92248,7 +93944,7 @@ var ts; break; case 3 /* MultiLineCommentTrivia */: combineAndAddMultipleSingleLineComments(); - out.push(createOutliningSpanFromBounds(pos, end)); + out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */)); singleLineCommentCount = 0; break; default: @@ -92259,12 +93955,12 @@ var ts; function combineAndAddMultipleSingleLineComments() { // Only outline spans of two or more consecutive single line comments if (singleLineCommentCount > 1) { - out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */)); } } } - function createOutliningSpanFromBounds(pos, end) { - return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { @@ -92298,7 +93994,7 @@ var ts; default: // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. - return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } case 239 /* ModuleBlock */: return spanForNode(n.parent); @@ -92330,14 +94026,14 @@ var ts; return undefined; } var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); - return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { if (hintSpan === void 0) { hintSpan = textSpan; } if (autoCollapse === void 0) { autoCollapse = false; } if (bannerText === void 0) { bannerText = "..."; } - return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); @@ -92620,13 +94316,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_13 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_4 = _loop_13(start); + var state_4 = _loop_15(start); if (typeof state_4 === "object") return state_4.value; } @@ -93172,6 +94868,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } + // Can't rename a module name. + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -93291,7 +94990,7 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_14 = function (declaration) { + var _loop_16 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -93305,7 +95004,7 @@ var ts; }; for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { var declaration = declarations_12[_b]; - var state_5 = _loop_14(declaration); + var state_5 = _loop_16(declaration); if (typeof state_5 === "object") return state_5.value; } @@ -93652,7 +95351,9 @@ var ts; program.getSemanticDiagnostics(sourceFile); var checker = program.getDiagnosticsProducingTypeChecker(); var diags = []; - if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))) { + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJavaScript(sourceFile); @@ -93691,19 +95392,42 @@ var ts; for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { var moduleSpecifier = _c[_b]; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); - var name_72 = importNameForConvertToDefaultImport(importNode); - if (!name_72) + var name = importNameForConvertToDefaultImport(importNode); + if (!name) continue; - var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { - diags.push(ts.createDiagnosticForNode(name_72, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); + diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); } } } - return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 213 /* VariableStatement */: + return statement.declarationList.declarations.some(function (decl) { + return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 215 /* ExpressionStatement */: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + var kind = ts.getSpecialPropertyAssignmentKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } function importNameForConvertToDefaultImport(node) { switch (node.kind) { case 243 /* ImportDeclaration */: @@ -94320,9 +96044,9 @@ var ts; return false; } // If the parent is not sourceFile or module block it is local variable - for (var parent_26 = declaration.parent; !ts.isFunctionBlock(parent_26); parent_26 = parent_26.parent) { + for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent_26.kind === 273 /* SourceFile */ || parent_26.kind === 239 /* ModuleBlock */) { + if (parent.kind === 273 /* SourceFile */ || parent.kind === 239 /* ModuleBlock */) { return false; } } @@ -94434,7 +96158,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_15 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -94453,7 +96177,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_15(opt); + _loop_17(opt); } return options; } @@ -94857,6 +96581,7 @@ var ts; rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. @@ -95317,6 +97042,9 @@ var ts; function isArrowFunctionContext(context) { return context.contextNode.kind === 192 /* ArrowFunction */; } + function isImportTypeContext(context) { + return context.contextNode.kind === 178 /* ImportType */; + } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; } @@ -95439,18 +97167,18 @@ var ts; // This array is used only during construction of the rulesbucket in the map var rulesBucketConstructionStateList = new Array(map.length); for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { - var rule = rules_1[_i]; - var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; - for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var rule_1 = rules_1[_i]; + var specificRule = rule_1.leftTokenRange.isSpecific && rule_1.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule_1.leftTokenRange.tokens; _a < _b.length; _a++) { var left = _b[_a]; - for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + for (var _c = 0, _d = rule_1.rightTokenRange.tokens; _c < _d.length; _c++) { var right = _d[_c]; var index = getRuleBucketIndex(left, right); var rulesBucket = map[index]; if (rulesBucket === undefined) { rulesBucket = map[index] = []; } - addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); + addRule(rulesBucket, rule_1.rule, specificRule, rulesBucketConstructionStateList, index); } } } @@ -96757,7 +98485,7 @@ var ts; NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; })(NextTokenKind || (NextTokenKind = {})); function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { - var nextToken = ts.findNextToken(precedingToken, current); + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); if (!nextToken) { return 0 /* Unknown */; } @@ -96806,9 +98534,10 @@ var ts; } function getContainingList(node, sourceFile) { if (node.parent) { + var end = node.end; switch (node.parent.kind) { case 161 /* TypeReference */: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); case 183 /* ObjectLiteralExpression */: return node.parent.properties; case 182 /* ArrayLiteralExpression */: @@ -96823,22 +98552,25 @@ var ts; case 163 /* ConstructorType */: case 158 /* ConstructSignature */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || + getListIfStartEndIsInListRange(node.parent.parameters, start, end); } case 234 /* ClassDeclaration */: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); case 187 /* NewExpression */: case 186 /* CallExpression */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || + getListIfStartEndIsInListRange(node.parent.arguments, start, end); } case 232 /* VariableDeclarationList */: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); case 246 /* NamedImports */: case 250 /* NamedExports */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); + case 179 /* ObjectBindingPattern */: + case 180 /* ArrayBindingPattern */: + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); } } return undefined; @@ -97160,10 +98892,10 @@ var ts; return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { - return node.getEnd(); + return end; } - var end = node.getEnd(); var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) ? newEnd @@ -97188,7 +98920,8 @@ var ts; this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + this.newFiles = []; + this.deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map } ChangeTracker.fromContext = function (context) { @@ -97232,35 +98965,14 @@ var ts; this.deleteNode(sourceFile, node); return this; } - var id = ts.getNodeId(node); - ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); - this.deletedNodesInLists[id] = true; - if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); - if (nextToken && isSeparator(node, nextToken)) { - // find first non-whitespace position in the leading trivia of the node - var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var nextElement = containingList[index + 1]; - /// find first non-whitespace position in the leading trivia of the next node - var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node - this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - } - } - else { - var prev = containingList[index - 1]; - if (this.deletedNodesInLists[ts.getNodeId(prev)]) { - var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var end = getAdjustedEndPosition(sourceFile, node, {}); - this.deleteRange(sourceFile, { pos: pos, end: end }); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); - } - } - } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!this.deletedNodesInLists.has(node), "Deleting a node twice"); + this.deletedNodesInLists.add(node); + this.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); return this; }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { @@ -97289,10 +99001,13 @@ var ts; if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 26 /* CommaToken */ ? next : undefined; + }; ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { - return this.replaceNode(sourceFile, oldNode, newNode, { - suffix: "," + this.newLineCharacter - }); + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } @@ -97326,7 +99041,8 @@ var ts; // Otherwise, add an extra new line immediately before the error span. var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); - var text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter; + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { @@ -97399,20 +99115,38 @@ var ts; }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); - var prefix = ""; - var suffix = this.newLineCharacter; - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { - prefix = this.newLineCharacter; - // For `class C {\n}`, don't add the trailing "\n" - if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { // TODO: GH#4130 remove 'as any' - suffix = ""; - } - } var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix }); + this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { + if (cls.members.length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + // For `class C {\n}`, don't add the trailing "\n" + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + } + else { + return { prefix: "", suffix: this.newLineCharacter }; + } + } + else { + return { prefix: this.newLineCharacter, suffix: "" }; + } + }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { if (needSemicolonBetween(after, newNode)) { // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI @@ -97421,9 +99155,13 @@ var ts; } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after)); + return endPosition; }; - ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; } @@ -97468,13 +99206,16 @@ var ts; this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } }; + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); + }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, * i.e. arguments in arguments lists, parameters in parameter lists etc. * Note that separators are part of the node in statements and class elements. */ - ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { - var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); return this; @@ -97592,6 +99333,19 @@ var ts; } }); }; + ChangeTracker.prototype.finishTrailingCommaAfterDeletingNodesInList = function () { + var _this = this; + this.deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !_this.deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } + }); + }; /** * Note: after calling this, the TextChanges object must be discarded! * @param validate only for tests @@ -97600,11 +99354,24 @@ var ts; */ ChangeTracker.prototype.getChanges = function (validate) { this.finishClassesWithNodesInsertedAtStart(); - return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + this.finishTrailingCommaAfterDeletingNodesInList(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); }; return ChangeTracker; }()); textChanges_3.ChangeTracker = ChangeTracker; + // find first non-whitespace position in the leading trivia of the node + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } function getClassBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } @@ -97614,15 +99381,16 @@ var ts; return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // order changes by start position - var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); - var _loop_16 = function (i) { + // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_16(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -97631,6 +99399,11 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter) { + var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -97980,10 +99753,11 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); - function getRefactorContextLength(context) { - return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); } - ts.getRefactorContextLength = getRefactorContextLength; + ts.getRefactorContextSpan = getRefactorContextSpan; })(ts || (ts = {})); /* @internal */ var ts; @@ -98051,7 +99825,7 @@ var ts; if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { if (!decl.typeParameters) { var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); - if (typeParameters) + if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); @@ -98087,18 +99861,18 @@ var ts; } function transformJSDocType(node) { switch (node.kind) { - case 276 /* JSDocAllType */: - case 277 /* JSDocUnknownType */: + case 278 /* JSDocAllType */: + case 279 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 280 /* JSDocOptionalType */: + case 282 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 279 /* JSDocNonNullableType */: + case 281 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 278 /* JSDocNullableType */: + case 280 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: return transformJSDocFunctionType(node); case 161 /* TypeReference */: return transformJSDocTypeReference(node); @@ -98122,7 +99896,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 282 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -98403,7 +100177,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -98450,8 +100224,8 @@ var ts; function forEachExportReference(sourceFile, cb) { sourceFile.forEachChild(function recur(node) { if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { - var parent_27 = node.parent; - cb(node, ts.isBinaryExpression(parent_27) && parent_27.left === node && parent_27.operatorToken.kind === 58 /* EqualsToken */); + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); } node.forEachChild(recur); }); @@ -98467,7 +100241,7 @@ var ts; case 186 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); } return false; } @@ -98540,27 +100314,30 @@ var ts; changes.deleteNode(sourceFile, assignment.parent); } else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + return true; } - changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); - return changedToDefaultExport; } } else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { convertNamedExport(sourceFile, assignment, changes, exports); } return false; - var _a; } /** * Convert `module.exports = { ... }` to individual exports.. * We can't always do this if the module has interesting members -- then it will be a default export instead. */ function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { case 155 /* GetAccessor */: case 156 /* SetAccessor */: @@ -98576,6 +100353,7 @@ var ts; ts.Debug.assertNever(prop); } }); + return statements && [statements, false]; } function convertNamedExport(sourceFile, assignment, changes, exports) { // If "originalKeywordKind" was set, this is e.g. `exports. @@ -98596,30 +100374,6 @@ var ts; convertExportsPropertyAssignment(assignment, sourceFile, changes); } } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; - switch (exported.kind) { - case 191 /* FunctionExpression */: - case 192 /* ArrowFunction */: { - // `module.exports = function f() {}` --> `export default function f() {}` - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 204 /* ClassExpression */: { - // `module.exports = class C {}` --> `export default class C {}` - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 186 /* CallExpression */: - if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) { - return convertReExportAll(exported.arguments[0], checker); - } - // falls through - default: - // `module.exports = 0;` --> `export default 0;` - return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; - } - } function convertReExportAll(reExported, checker) { // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` var moduleSpecifier = reExported.text; @@ -98695,7 +100449,7 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -98706,7 +100460,7 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } @@ -98732,16 +100486,16 @@ var ts; // This was a use of a different symbol with the same name, due to shadowing. Ignore. continue; } - var parent_28 = use.parent; - if (ts.isPropertyAccessExpression(parent_28)) { - var expression = parent_28.expression, propertyName = parent_28.name.text; + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` var idName = namedBindingsNames.get(propertyName); if (idName === undefined) { idName = makeUniqueName(propertyName, identifiers); namedBindingsNames.set(propertyName, idName); } - changes.replaceNode(file, parent_28, ts.createIdentifier(idName)); + changes.replaceNode(file, parent, ts.createIdentifier(idName)); } else { needDefaultImport = true; @@ -98755,7 +100509,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -98797,17 +100551,9 @@ var ts; } function makeSingleImport(localName, propertyName, moduleSpecifier) { return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); } - function makeImport(name, namedImports, moduleSpecifier) { - return makeImportDeclaration(name, namedImports, moduleSpecifier); - } - function makeImportDeclaration(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier); - } - codefix.makeImportDeclaration = makeImportDeclaration; function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); } @@ -98968,7 +100714,7 @@ var ts; var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } @@ -99014,11 +100760,11 @@ var ts; if (context.symbolToken && ts.isIdentifier(context.symbolToken)) { for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) { var declaration = existingImports_1[_i].declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); + var namespace_2 = getNamespaceImportName(declaration); + if (namespace_2) { + var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2)); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken)); } } } @@ -99085,12 +100831,6 @@ var ts; return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); } } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; - }) || false; - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -99104,274 +100844,15 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { - var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(sourceFile); + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences); return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - /** - * Looks for a existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var count = 0; - for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { - count++; - } - return count; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName); - } - } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { var fromExistingImport = ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -99390,7 +100871,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences); for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) { var info = newImportInfos_1[_i]; addNew.push(getCodeActionForNewImport(ctx, info)); @@ -99469,10 +100950,10 @@ var ts; } if (!ts.isUMDExportSymbol(umdSymbol)) { // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - var parent_29 = token.parent; - var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent_29); - if ((ts.isJsxOpeningLikeElement && parent_29.tagName === token) || parent_29.kind === 259 /* JsxOpeningFragment */) { - umdSymbol = checker.resolveName(checker.getJsxNamespace(parent_29), isNodeOpeningLikeElement ? parent_29.tagName : parent_29, 67216319 /* Value */, /*excludeGlobals*/ false); + var parent = token.parent; + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent); + if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 259 /* JsxOpeningFragment */) { + umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false); } } if (ts.isUMDExportSymbol(umdSymbol)) { @@ -99686,9 +101167,9 @@ var ts; } else { var meaning = ts.getMeaningFromLocation(node); - var name_73 = ts.getTextOfNode(node); - ts.Debug.assert(name_73 !== undefined, "name should be defined"); - suggestion = checker.getSuggestionForNonexistentSymbol(node, name_73, convertSemanticMeaningToSymbolFlags(meaning)); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; } @@ -99848,7 +101329,24 @@ var ts; /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + } + // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; } function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. @@ -100160,6 +101658,7 @@ var ts; ts.Diagnostics._0_is_declared_but_never_used.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -100170,9 +101669,13 @@ var ts; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start, /*deleted*/ undefined); }); + if (delDestructure.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined); }); if (deletion.length) { result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } @@ -100183,36 +101686,69 @@ var ts; return result; }, fixIds: [fixIdPrefix, fixIdDelete], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var sourceFile = context.sourceFile; - var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); - switch (context.fixId) { - case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); - } - break; - case fixIdDelete: - var importDecl = tryGetFullImport(diag.file, diag.start); - if (importDecl) { - changes.deleteNode(sourceFile, importDecl); - } - else { - tryDeleteDeclaration(changes, sourceFile, token); - } - break; - default: - ts.Debug.fail(JSON.stringify(context.fixId)); - } - }); }, + getAllCodeActions: function (context) { + // Track a set of deleted nodes that may be ancestors of other marked for deletion -- only delete the ancestors. + var deleted = new NodeSet(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var sourceFile = context.sourceFile; + var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: + // Ignore if this range was already deleted. + if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); })) + break; + var importDecl = tryGetFullImport(diag.file, diag.start); + if (importDecl) { + changes.deleteNode(sourceFile, importDecl); + } + else { + if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) { + tryDeleteDeclaration(changes, sourceFile, token, deleted); + } + } + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, }); // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(sourceFile, pos) { var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; } + function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) { + var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent)) + return false; + var decl = startToken.parent.parent; + switch (decl.kind) { + case 231 /* VariableDeclaration */: + tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors); + break; + case 148 /* Parameter */: + if (deletedAncestors) + deletedAncestors.add(decl); + changes.deleteNodeInList(sourceFile, decl); + break; + case 181 /* BindingElement */: + if (deletedAncestors) + deletedAncestors.add(decl); + changes.deleteNode(sourceFile, decl); + break; + default: + return ts.Debug.assertNever(decl); + } + return true; + } function getToken(sourceFile, pos) { - var token = ts.findPrecedingToken(pos, sourceFile); + var token = ts.findPrecedingToken(pos, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); // this handles var ["computed"] = 12; return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token; } @@ -100237,38 +101773,45 @@ var ts; } return false; } - function tryDeleteDeclaration(changes, sourceFile, token) { + function tryDeleteDeclaration(changes, sourceFile, token, deletedAncestors) { switch (token.kind) { case 71 /* Identifier */: - tryDeleteIdentifier(changes, sourceFile, token); + tryDeleteIdentifier(changes, sourceFile, token, deletedAncestors); break; case 151 /* PropertyDeclaration */: case 245 /* NamespaceImport */: + if (deletedAncestors) + deletedAncestors.add(token.parent); changes.deleteNode(sourceFile, token.parent); break; default: - tryDeleteDefault(changes, sourceFile, token); + tryDeleteDefault(changes, sourceFile, token, deletedAncestors); } } - function tryDeleteDefault(changes, sourceFile, token) { + function tryDeleteDefault(changes, sourceFile, token, deletedAncestors) { if (ts.isDeclarationName(token)) { + if (deletedAncestors) + deletedAncestors.add(token.parent); changes.deleteNode(sourceFile, token.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + if (deletedAncestors) + deletedAncestors.add(token.parent.parent); changes.deleteNode(sourceFile, token.parent.parent); } } - function tryDeleteIdentifier(changes, sourceFile, identifier) { + function tryDeleteIdentifier(changes, sourceFile, identifier, deletedAncestors) { var parent = identifier.parent; switch (parent.kind) { case 231 /* VariableDeclaration */: - tryDeleteVariableDeclaration(changes, sourceFile, parent); + tryDeleteVariableDeclaration(changes, sourceFile, parent, deletedAncestors); break; case 147 /* TypeParameter */: - var typeParameters = parent.parent.typeParameters; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(parent.parent); if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; + var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, end, /*includeJsDocComment*/ false); ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); changes.deleteNodeRange(sourceFile, previousToken, nextToken); @@ -100299,6 +101842,20 @@ var ts; changes.deleteNodeInList(sourceFile, parent); } break; + case 181 /* BindingElement */: { + var pattern = parent.parent; + switch (pattern.kind) { + case 180 /* ArrayBindingPattern */: + changes.deleteNode(sourceFile, parent); // Don't delete ',' + break; + case 179 /* ObjectBindingPattern */: + changes.deleteNodeInList(sourceFile, parent); + break; + default: + return ts.Debug.assertNever(pattern); + } + break; + } // handle case where 'import a = A;' case 242 /* ImportEqualsDeclaration */: var importEquals = ts.getAncestor(identifier, 242 /* ImportEqualsDeclaration */); @@ -100337,7 +101894,7 @@ var ts; tryDeleteNamedImportBinding(changes, sourceFile, parent); break; default: - tryDeleteDefault(changes, sourceFile, identifier); + tryDeleteDefault(changes, sourceFile, identifier, deletedAncestors); break; } } @@ -100360,15 +101917,19 @@ var ts; } } // token.parent is a variableDeclaration - function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { + function tryDeleteVariableDeclaration(changes, sourceFile, varDecl, deletedAncestors) { switch (varDecl.parent.parent.kind) { case 219 /* ForStatement */: { var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; if (forInitializer.declarations.length === 1) { + if (deletedAncestors) + deletedAncestors.add(forInitializer); changes.deleteNode(sourceFile, forInitializer); } else { + if (deletedAncestors) + deletedAncestors.add(varDecl); changes.deleteNodeInList(sourceFile, varDecl); } break; @@ -100377,6 +101938,8 @@ var ts; var forOfStatement = varDecl.parent.parent; ts.Debug.assert(forOfStatement.initializer.kind === 232 /* VariableDeclarationList */); var forOfInitializer = forOfStatement.initializer; + if (deletedAncestors) + deletedAncestors.add(forOfInitializer.declarations[0]); changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); break; case 220 /* ForInStatement */: @@ -100385,13 +101948,131 @@ var ts; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { + if (deletedAncestors) + deletedAncestors.add(variableStatement); changes.deleteNode(sourceFile, variableStatement); } else { + if (deletedAncestors) + deletedAncestors.add(varDecl); changes.deleteNodeInList(sourceFile, varDecl); } } } + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + switch (container.kind) { + case 216 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + break; + } + // falls through + case 218 /* WhileStatement */: + case 219 /* ForStatement */: + changes.deleteNode(sourceFile, container); + break; + default: + if (ts.isBlock(statement.parent)) { + split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); + } + else { + changes.deleteNode(sourceFile, statement); + } + } + } + function shouldRemove(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 235 /* InterfaceDeclaration */: + case 236 /* TypeAliasDeclaration */: + return true; + case 238 /* ModuleDeclaration */: + return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; + case 237 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + } + } + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + ts.Debug.assert(index !== -1); + return arr.slice(index); + } + // Calls 'cb' with the start and end of each range where 'pred' is true. + function split(arr, pred, cb) { + ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -100413,7 +102094,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 278 /* JSDocNullableType */) { + if (typeNode.kind === 280 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -100433,7 +102114,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 278 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; + var fixedType = typeNode.kind === 280 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -100811,16 +102492,16 @@ var ts; } var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var seenFunctions = ts.createMap(); + var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, markSeen); }); }, }); @@ -100834,7 +102515,7 @@ var ts; return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { return undefined; } @@ -100843,17 +102524,18 @@ var ts; // Variable and Property declarations case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) { + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); return symbol.valueDeclaration; } + return undefined; } } var containingFunction = ts.getContainingFunction(token); @@ -100869,7 +102551,7 @@ var ts; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { + if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); return param; @@ -101061,6 +102743,16 @@ var ts; case 185 /* ElementAccessExpression */: inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); break; + case 231 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through default: return inferTypeFromContextualType(node, checker, usageContext); } @@ -101232,7 +102924,7 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); + return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); @@ -101349,7 +103041,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -101506,6 +103198,290 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +// Used by importFixes to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + // For each symlink/original for a module, returns a list of ways to import that file. + function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var compilerOptions = program.getCompilerOptions(); + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName); + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + // For a type definition, we can strip `/index` even with classic resolution. + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -101575,7 +103551,40 @@ var ts; } } function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + ts.Debug.assert(token.kind === 91 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 178 /* ImportType */); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + changes.replaceNode(sourceFile, importType, newTypeNode); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -101593,7 +103602,7 @@ var ts; * Exported for tests. */ function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -101662,7 +103671,7 @@ var ts; extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); if (parsedFunctionIndexMatch) { @@ -102774,8 +104783,8 @@ var ts; i_1++; } // Note that we add the current node's type parameters *after* updating the corresponding scope. - if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { - for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { var typeParameterDecl = _b[_a]; var typeParameter = checker.getTypeAtLocation(typeParameterDecl); if (allTypeParameterUsages.has(typeParameter.id.toString())) { @@ -102797,7 +104806,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_17 = function (i) { + var _loop_19 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -102837,21 +104846,11 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_17(i); + _loop_19(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; - function hasTypeParameters(node) { - return ts.isDeclarationWithTypeParameters(node) && - node.typeParameters !== undefined && - node.typeParameters.length > 0; - } function isInGenericContext(node) { - for (; node; node = node.parent) { - if (hasTypeParameters(node)) { - return true; - } - } - return false; + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); } function recordTypeParameterUsages(type) { // PERF: This is potentially very expensive. `type` could be a library type with @@ -103116,8 +105115,8 @@ var ts; var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition; - if (!getConvertibleFieldAtPosition(file, startPosition)) + var file = context.file; + if (!getConvertibleFieldAtPosition(context, file)) return undefined; return [{ name: actionName, @@ -103131,27 +105130,46 @@ var ts; }]; } function getEditsForAction(context, _actionName) { - var file = context.file, startPosition = context.startPosition; - var fieldInfo = getConvertibleFieldAtPosition(file, startPosition); + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context, file); if (!fieldInfo) return undefined; var isJS = ts.isSourceFileJavaScript(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration; + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); var isInClassLike = ts.isClassLike(container); + // avoid Readonly modifier because it will convert to get accessor + var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; var accessorModifiers = isInClassLike - ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 /* Private */ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) : declaration.modifiers + ? !modifierFlags || modifierFlags & 8 /* Private */ + ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined; var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined; - updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container); + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); - var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); insertAccessor(changeTracker, file, getAccessor, declaration, container); - insertAccessor(changeTracker, file, setAccessor, declaration, container); + if (isReadonly) { + // readonly modifier only existed in classLikeDeclaration + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } var edits = changeTracker.getChanges(); var renameFilename = file.fileName; - var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1; - var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false); + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function isConvertableName(name) { @@ -103171,24 +105189,32 @@ var ts; var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined); return modifiers && ts.createNodeArray(modifiers); } - function getConvertibleFieldAtPosition(file, startPosition) { + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + function getConvertibleFieldAtPosition(context, file) { + var startPosition = context.startPosition, endPosition = context.endPosition; var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); - // make sure propertyDeclaration have AccessibilityModifier or Static Modifier - var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */; - if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier + var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) + || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; - var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name); - var accessorName = createPropertyName(declaration.name.text, declaration.name); - ts.suppressLeadingAndTrailingTrivia(fieldName); - ts.suppressLeadingAndTrailingTrivia(declaration); + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file.text), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file.text) : name, declaration.name); return { isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), container: declaration.kind === 148 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name, declaration: declaration, fieldName: fieldName, accessorName: accessorName, + renameAccessor: startWithUnderscore }; } function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { @@ -103212,16 +105238,11 @@ var ts; var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } - function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) { - var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer); - changeTracker.insertNodeAtClassStart(file, classLikeContainer, property); - changeTracker.deleteNodeInList(file, declaration); - } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); changeTracker.replacePropertyAssignment(file, declaration, assignment); } - function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) { + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { if (ts.isPropertyDeclaration(declaration)) { updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); } @@ -103229,19 +105250,636 @@ var ts; updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container); + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { ts.isParameterPropertyDeclaration(declaration) ? changeTracker.insertNodeAtClassStart(file, container, accessor) - : changeTracker.insertNodeAfter(file, declaration, accessor); + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + if (!constructor.body) + return; + var file = context.file, program = context.program, cancellationToken = context.cancellationToken; + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); }); + ts.forEach(referenceEntries, function (entry) { + var parent = entry.parent; + var accessorName = ts.createIdentifier(fieldName.text); + var node = ts.isBinaryExpression(parent) + ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) + : ts.isPropertyAccessExpression(parent) + ? ts.updatePropertyAccess(parent, parent.expression, accessorName) + : ts.Debug.fail("Unexpected write access token"); + changeTracker.replaceNode(file, parent, node); + }); } })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + return undefined; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getFirstAndLastStatementToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + // Can't only partially include the start node or be partially into the next node + if (range.pos > statements[startNodeIndex].getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + // Can't be partially into the next node + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + } + function doChange(oldFile, program, toMove, changes, host) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + // If previous file was global, this is easy. + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. + function getStatementsToMove(context) { + var statements = context.file.statements; + var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var all = []; + var ranges = []; + var rangeToMove = statements.slice(first, afterLast); + ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { + for (var i = start; i < afterEnd; i++) + all.push(rangeToMove[i]); + ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); + }); + return { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 243 /* ImportDeclaration */: + return true; + case 242 /* ImportEqualsDeclaration */: + return !ts.hasModifier(node, 1 /* Export */); + case 213 /* VariableStatement */: + return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + if (importsFromNewFile) { + changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last; + changes.deleteNodeRange(sourceFile, first_1, last_3); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_20 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_21 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_21(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_20(sourceFile); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 243 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 242 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path); + } + else { + ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. + var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2 /* Const */; } + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 243 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 242 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.deleteNode(sourceFile, importDecl); + } + break; + case 231 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 245 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.deleteNode(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.deleteNode(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.deleteNode(sourceFile, namedBindings); + } + else if (namedBindings.kind === 246 /* NamedImports */) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.deleteNodeInList(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 71 /* Identifier */: + if (isUnused(name)) { + changes.deleteNode(sourceFile, name); + } + break; + case 180 /* ArrayBindingPattern */: + break; + case 179 /* ObjectBindingPattern */: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.deleteNode(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.deleteNode(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512 /* Default */)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + // Below should all be utilities + function isInImport(decl) { + switch (decl.kind) { + case 242 /* ImportEqualsDeclaration */: + case 247 /* ImportSpecifier */: + case 244 /* ImportClause */: + return true; + case 231 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 181 /* BindingElement */: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 243 /* ImportDeclaration */: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 242 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : undefined; + case 231 /* VariableDeclaration */: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 245 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 71 /* Identifier */: + return keep(name) ? name : undefined; + case 180 /* ArrayBindingPattern */: + return name; + case 179 /* ObjectBindingPattern */: { + // We can't handle nested destructurings or property names well here, so just copy them all. + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = /** @class */ (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 233 /* FunctionDeclaration */: + case 234 /* ClassDeclaration */: + case 238 /* ModuleDeclaration */: + case 237 /* EnumDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 242 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 233 /* FunctionDeclaration */: + case 234 /* ClassDeclaration */: + case 238 /* ModuleDeclaration */: + case 237 /* EnumDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 242 /* ImportEqualsDeclaration */: + return cb(statement); + case 213 /* VariableStatement */: + return ts.forEach(statement.declarationList.declarations, cb); + case 215 /* ExpressionStatement */: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + ? cb(statement) + : undefined; + } + } + } + function nameOfTopLevelDeclaration(d) { + return d.kind === 215 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + return ts.isVariableDeclaration(d) ? d.parent.parent : d; + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); + switch (d.kind) { + case 233 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 234 /* ClassDeclaration */: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 213 /* VariableStatement */: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 238 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 237 /* EnumDeclaration */: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 236 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 235 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 242 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 215 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 233 /* FunctionDeclaration */: + case 234 /* ClassDeclaration */: + return [decl.name.text]; + case 213 /* VariableStatement */: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 238 /* ModuleDeclaration */: + case 237 /* EnumDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 242 /* ImportEqualsDeclaration */: + return undefined; + case 215 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + ts.Debug.assertNever(decl); + } + } + /** Creates `exports.x = x;` */ + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var sourcemaps; (function (sourcemaps) { @@ -103563,7 +106201,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 275 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 277 /* FirstJSDocNode */ || kid.kind > 297 /* LastJSDocNode */; }); return child.kind < 145 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -103633,7 +106271,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(298 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -104156,6 +106794,9 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -104185,9 +106826,18 @@ var ts; return ts.isString(info) ? undefined : info; }; HostCache.prototype.getRootFileNames = function () { - return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { - return ts.isString(entry) ? entry : entry.hostFileName; + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6 /* JSON */) { + names.push(entry.hostFileName); + } + } }); + return names; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); @@ -104363,6 +107013,7 @@ var ts; } ts.createSourceFileLikeCache = createSourceFileLikeCache; function createLanguageService(host, documentRegistry, syntaxOnly) { + var _a; if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } if (syntaxOnly === void 0) { syntaxOnly = false; } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -104466,7 +107117,14 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: hostCache.getProjectReferences() + }; + program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; @@ -104670,6 +107328,11 @@ var ts; } return checker.getSymbolAtLocation(node); } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); + return file.getLineAndCharacterOfPosition(position); + } // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/gm; var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; @@ -104731,8 +107394,8 @@ var ts; } possibleMapLocations.push(fileName + ".map"); for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { - var location_4 = possibleMapLocations_1[_i]; - var mapPath = ts.toPath(location_4, ts.getDirectoryPath(fileName), getCanonicalFileName); + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); if (host.fileExists(mapPath)) { return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); } @@ -104741,27 +107404,28 @@ var ts; } function makeGetTargetOfMappedPosition(extract, create) { return getTargetOfMappedPosition; - function getTargetOfMappedPosition(input) { + function getTargetOfMappedPosition(input, original) { + if (original === void 0) { original = input; } var info = extract(input); if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { - var file = program.getSourceFile(info.fileName); - if (!file) { + var file_18 = program.getSourceFile(info.fileName); + if (!file_18) { var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); - file = sourcemappedFileCache.get(path); + file_18 = sourcemappedFileCache.get(path); } - if (!file) { + if (!file_18) { return input; } - var mapper = getSourceMapper(info.fileName, file); + var mapper = getSourceMapper(info.fileName, file_18); var newLoc = mapper.getOriginalPosition(info); if (newLoc === info) return input; - return getTargetOfMappedPosition(create(newLoc, input)); + return getTargetOfMappedPosition(create(newLoc, input, original), original); } return input; } } - var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({ containerKind: info.containerKind, containerName: info.containerName, fileName: newLoc.fileName, @@ -104770,10 +107434,12 @@ var ts; textSpan: { start: newLoc.position, length: info.textSpan.length - } + }, + originalFileName: original.fileName, + originalTextSpan: original.textSpan }); }); function getTargetOfMappedDeclarationFiles(infos) { - return ts.map(infos, getTargetOfMappedDeclarationInfo); + return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); }); } /// Goto definition function getDefinitionAtPosition(fileName, position) { @@ -104806,10 +107472,12 @@ var ts; textSpan: { start: newLoc.position, length: info.textSpan.length - } + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan }); }); function getTargetOfMappedImplementationLocations(infos) { - return ts.map(infos, getTargetOfMappedImplementationLocation); + return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); }); } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); @@ -105317,8 +107985,8 @@ var ts; getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: toLineColumnOffset }; - var _a; } ts.createLanguageService = createLanguageService; /* @internal */ @@ -105389,20 +108057,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_6 = []; + var result_7 = []; var symbol = type.getProperty(name); if (type.flags & 131072 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_7.push(symbol); } }); - return result_6; + return result_7; } if (symbol) { - result_6.push(symbol); - return result_6; + result_7.push(symbol); + return result_7; } } return undefined; @@ -105469,7 +108137,7 @@ var ts; return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { - return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { @@ -105484,7 +108152,7 @@ var ts; return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } function spanInNextNode(node) { - return spanInNode(ts.findNextToken(node, node.parent)); + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); } function spanInNode(node) { if (node) { @@ -107042,8 +109710,8 @@ var ts; var before = log && self.host.getMemoryUsage(); self.host.gc(); if (log) { - var after = self.host.getMemoryUsage(); - self.logger.perftrc("GC::before " + before + ", after " + after); + var after_1 = self.host.getMemoryUsage(); + self.logger.perftrc("GC::before " + before + ", after " + after_1); } }; return GcTimer; @@ -107804,7 +110472,7 @@ var ts; })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); /* @internal */ function countEachFileTypes(infos) { - var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; + var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0, deferred: 0 }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; switch (info.scriptKind) { @@ -107822,6 +110490,9 @@ var ts; case 4 /* TSX */: result.tsx += 1; break; + case 7 /* Deferred */: + result.deferred += 1; + break; } } return result; @@ -107905,7 +110576,7 @@ var ts; this.compilerOptions.allowNonTsExtensions = true; this.compilerOptions.allowJs = true; } - else if (hasExplicitListOfFiles || this.compilerOptions.allowJs) { + else if (hasExplicitListOfFiles || this.compilerOptions.allowJs || this.projectService.hasDeferredExtension()) { // If files are listed explicitly or allowJs is specified, allow all extensions this.compilerOptions.allowNonTsExtensions = true; } @@ -107976,6 +110647,9 @@ var ts; Project.prototype.getProjectVersion = function () { return this.projectStateVersion.toString(); }; + Project.prototype.getProjectReferences = function () { + return undefined; + }; Project.prototype.getScriptFileNames = function () { var _this = this; if (!this.rootFiles) { @@ -108045,6 +110719,9 @@ var ts; Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }; + Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) { + return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile); + }; Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; @@ -108426,15 +111103,16 @@ var ts; * @returns: true if set of files in the project stays the same and false - otherwise. */ Project.prototype.updateGraph = function () { + var _a; this.resolutionCache.startRecordingFilesWithChangedResolutions(); var hasNewProgram = this.updateGraphWorker(); var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; this.hasAddedorRemovedFiles = false; var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { - var file = changedFiles_1[_i]; + var file_19 = changedFiles_1[_i]; // delete cached information for changed files - this.cachedUnresolvedImportsPerFile.delete(file); + this.cachedUnresolvedImportsPerFile.delete(file_19); } // update builder only if language service is enabled // otherwise tell it to drop its internal state @@ -108448,11 +111126,11 @@ var ts; if (hasNewProgram || changedFiles.length) { var result = void 0; var ambientModules = this.program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); - for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { - var sourceFile = _b[_a]; + for (var _b = 0, _c = this.program.getSourceFiles(); _b < _c.length; _b++) { + var sourceFile = _c[_b]; var unResolved = this.extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules); if (unResolved !== server.emptyArray) { - (_c = (result || (result = []))).push.apply(_c, unResolved); + (_a = (result || (result = []))).push.apply(_a, unResolved); } } this.lastCachedUnresolvedImportsList = result ? server.toDeduplicatedSortedArray(result) : server.emptyArray; @@ -108466,7 +111144,6 @@ var ts; this.projectProgramVersion++; } return !hasNewProgram; - var _c; }; /*@internal*/ Project.prototype.updateTypingFiles = function (typingFiles) { @@ -108578,9 +111255,9 @@ var ts; var sourceFiles = this.program.getSourceFiles(); var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; if (writeProjectFileNames) { - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var file = sourceFiles_7[_i]; - strBuilder += "\t" + file.fileName + "\n"; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var file_20 = sourceFiles_8[_i]; + strBuilder += "\t" + file_20.fileName + "\n"; } } return strBuilder; @@ -108666,7 +111343,7 @@ var ts; // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_18 = function (globalPluginName) { + var _loop_22 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -108681,7 +111358,7 @@ var ts; // Enable global plugins with synthetic configuration entries for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_18(globalPluginName); + _loop_22(globalPluginName); } } }; @@ -108691,15 +111368,19 @@ var ts; var log = function (message) { _this.projectService.logger.info(message); }; - for (var _i = 0, searchPaths_1 = searchPaths; _i < searchPaths_1.length; _i++) { - var searchPath = searchPaths_1[_i]; - var resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log); - if (resolvedModule) { - this.enableProxy(resolvedModule, pluginConfigEntry); - return; - } + var resolvedModule = ts.firstDefined(searchPaths, function (searchPath) { + return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log); + }); + if (resolvedModule) { + this.enableProxy(resolvedModule, pluginConfigEntry); } - this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); + else { + this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); + } + }; + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + Project.prototype.refreshDiagnostics = function () { + this.projectService.sendProjectsUpdatedInBackgroundEvent(); }; Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { try { @@ -108834,9 +111515,10 @@ var ts; var ConfiguredProject = /** @class */ (function (_super) { __extends(ConfiguredProject, _super); /*@internal*/ - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost) { + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.projectReferences = projectReferences; /** Ref count to the project when opened from external project */ _this.externalProjectRefCount = 0; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); @@ -108867,6 +111549,12 @@ var ts; ConfiguredProject.prototype.getConfigFilePath = function () { return server.asNormalizedPath(this.getProjectName()); }; + ConfiguredProject.prototype.getProjectReferences = function () { + return this.projectReferences; + }; + ConfiguredProject.prototype.updateReferences = function (refs) { + this.projectReferences = refs; + }; ConfiguredProject.prototype.enablePlugins = function () { var host = this.projectService.host; var options = this.getCompilationSettings(); @@ -109025,6 +111713,7 @@ var ts; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; server.ProjectInfoTelemetryEvent = "projectInfo"; + server.OpenFileInfoTelemetryEvent = "openFileInfo"; function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { var map = ts.createMap(); for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { @@ -109197,6 +111886,8 @@ var ts; * Container of all known scripts */ this.filenameToScriptInfo = ts.createMap(); + // Set of all '.js' files ever opened. + this.allJsFilesForOpenFileTelemetry = ts.createMap(); /** * maps external project file name to list of config files that were the part of this project */ @@ -109388,6 +112079,7 @@ var ts; ProjectService.prototype.hasPendingProjectUpdate = function (project) { return this.pendingProjectUpdates.has(project.getProjectName()); }; + /* @internal */ ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () { var _this = this; if (!this.eventHandler) { @@ -109407,11 +112099,13 @@ var ts; this.delayEnsureProjectForOpenFiles(); }; ProjectService.prototype.delayUpdateProjectGraphs = function (projects) { - for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { - var project = projects_2[_i]; - this.delayUpdateProjectGraph(project); + if (projects.length) { + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var project = projects_2[_i]; + this.delayUpdateProjectGraph(project); + } + this.delayEnsureProjectForOpenFiles(); } - this.delayEnsureProjectForOpenFiles(); }; ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) { ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); @@ -109510,7 +112204,6 @@ var ts; this.handleDeletedFile(info); } else if (!info.isScriptOpen()) { - ts.Debug.assert(info.containingProjects.length !== 0); // file has been changed which might affect the set of referenced files in projects that include // this file and set of inferred projects info.delayReloadNonMixedContentFile(); @@ -109632,7 +112325,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_19 = function (inferredProject) { + var _loop_23 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -109653,7 +112346,7 @@ var ts; // Note that we need to create a copy of the array since the list of project can change for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_19(inferredProject); + _loop_23(inferredProject); } } return project; @@ -109927,13 +112620,17 @@ var ts; * the newly opened file. */ ProjectService.prototype.forEachConfigFileLocation = function (info, action) { + var _this = this; if (this.syntaxOnly) { return undefined; } ts.Debug.assert(this.openFiles.has(info.path)); var projectRootPath = this.openFiles.get(info.path); var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); - while (!projectRootPath || ts.containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames)) { + var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); }; + // If projectRootPath doesnt contain info.path, then do normal search for config file + var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot(); + do { var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); @@ -109950,7 +112647,7 @@ var ts; break; } searchPath = parentPath; - } + } while (anySearchPathOk || isSearchPathInProjectRoot()); return undefined; }; /** @@ -110042,7 +112739,8 @@ var ts; configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave + compileOnSave: parsedCommandLine.compileOnSave, + projectReferences: parsedCommandLine.projectReferences }; return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; }; @@ -110098,11 +112796,11 @@ var ts; return; } this.seenProjects.set(projectKey, true); - if (!this.eventHandler) { + if (!this.eventHandler || !this.host.createSHA256Hash) { return; } var data = { - projectId: this.host.createHash(projectKey), + projectId: this.host.createSHA256Hash(projectKey), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -110145,7 +112843,7 @@ var ts; var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); project.configFileSpecs = configFileSpecs; // TODO: We probably should also watch the configFiles that are extended project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); @@ -110252,6 +112950,7 @@ var ts; // Update the project project.configFileSpecs = configFileSpecs; project.setProjectErrors(configFileErrors); + project.updateReferences(projectOptions.projectReferences); var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); if (lastFileExceededProgramSize) { project.disableLanguageService(lastFileExceededProgramSize); @@ -110375,7 +113074,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_20 = function (project) { + var _loop_24 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -110392,7 +113091,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_20(project); + _loop_24(project); } } } @@ -110709,8 +113408,16 @@ var ts; } }); this.printProjects(); + this.telemetryOnOpenFile(info); return { configFileName: configFileName, configFileErrors: configFileErrors }; }; + ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) { + if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { + return; + } + var info = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path).checkJsDirective }; + this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } }); + }; /** * Close file whose contents is managed by the client * @param filename is absolute pathname @@ -110723,13 +113430,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_21 = function (proj) { + var _loop_25 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_21(proj); + _loop_25(proj); } }; /* @internal */ @@ -110744,25 +113451,25 @@ var ts; ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { if (openFiles) { for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { - var file = openFiles_1[_i]; - var scriptInfo = this.getScriptInfo(file.fileName); + var file_21 = openFiles_1[_i]; + var scriptInfo = this.getScriptInfo(file_21.fileName); ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already"); - var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); - this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); + var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file_21.fileName); + this.openClientFileWithNormalizedPath(normalizedPath, file_21.content, tryConvertScriptKindName(file_21.scriptKind), file_21.hasMixedContent); } } if (changedFiles) { for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) { - var file = changedFiles_2[_a]; - var scriptInfo = this.getScriptInfo(file.fileName); + var file_22 = changedFiles_2[_a]; + var scriptInfo = this.getScriptInfo(file_22.fileName); ts.Debug.assert(!!scriptInfo); - this.applyChangesToFile(scriptInfo, file.changes); + this.applyChangesToFile(scriptInfo, file_22.changes); } } if (closedFiles) { for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { - var file = closedFiles_1[_b]; - this.closeClientFile(file); + var file_23 = closedFiles_1[_b]; + this.closeClientFile(file_23); } } }; @@ -110838,15 +113545,15 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_22 = function (name_74) { - var rule = this_2.safelist[name_74]; + var _loop_26 = function (name) { + var rule_2 = this_2.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; - if (rule.match.test(root)) { - this_2.logger.info("Excluding files based on rule " + name_74 + " matching file '" + root + "'"); + if (rule_2.match.test(root)) { + this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'"); // If the file matches, collect its types packages and exclude rules - if (rule.types) { - for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { + if (rule_2.types) { + for (var _a = 0, _b = rule_2.types; _a < _b.length; _a++) { var type = _b[_a]; // Best-effort de-duping here - doesn't need to be unduplicated but // we don't want the list to become a 400-element array of just 'kendo' @@ -110855,9 +113562,9 @@ var ts; } } } - if (rule.exclude) { - var _loop_23 = function (exclude) { - var processedRule = root.replace(rule.match, function () { + if (rule_2.exclude) { + var _loop_28 = function (exclude) { + var processedRule = root.replace(rule_2.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { groups[_i] = arguments[_i]; @@ -110868,7 +113575,7 @@ var ts; if (typeof groupNumberOrString === "number") { if (!ts.isString(groups[groupNumberOrString])) { // Specification was wrong - exclude nothing! - _this.logger.info("Incorrect RegExp specification in safelist rule " + name_74 + " - not enough groups"); + _this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups"); // * can't appear in a filename; escape it because it's feeding into a RegExp return "\\*"; } @@ -110881,9 +113588,9 @@ var ts; excludeRules.push(processedRule); } }; - for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { + for (var _c = 0, _d = rule_2.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_23(exclude); + _loop_28(exclude); } } else { @@ -110898,12 +113605,12 @@ var ts; }; var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { - var name_74 = _a[_i]; - _loop_22(name_74); + var name = _a[_i]; + _loop_26(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_24 = function (i) { + var _loop_27 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -110941,7 +113648,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_24(i); + _loop_27(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -110963,15 +113670,15 @@ var ts; var tsConfigFiles; var rootFiles = []; for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { - var file = _a[_i]; - var normalized = server.toNormalizedPath(file.fileName); + var file_24 = _a[_i]; + var normalized = server.toNormalizedPath(file_24.fileName); if (server.getBaseConfigFileName(normalized)) { if (!this.syntaxOnly && this.host.fileExists(normalized)) { (tsConfigFiles || (tsConfigFiles = [])).push(normalized); } } else { - rootFiles.push(file); + rootFiles.push(file_24); } } // sort config files to simplify comparison later @@ -111055,6 +113762,15 @@ var ts; this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); } }; + ProjectService.prototype.hasDeferredExtension = function () { + for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { + var extension = _a[_i]; + if (extension.scriptKind === 7 /* Deferred */) { + return true; + } + } + return false; + }; /** Makes a filename safe to insert in a RegExp */ ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; return ProjectService; @@ -111266,6 +113982,7 @@ var ts; } var Session = /** @class */ (function () { function Session(opts) { + var _a; var _this = this; this.changeSeq = 0; this.handlers = ts.createMapFromTemplate((_a = {}, @@ -111600,7 +114317,6 @@ var ts; }; this.projectService = new server.ProjectService(settings); this.gcTimer = new server.GcTimer(this.host, /*delay*/ 7000, this.logger); - var _a; } Session.prototype.sendRequestCompletedEvent = function (requestId) { this.event({ request_seq: requestId }, "requestCompleted"); @@ -111862,9 +114578,7 @@ var ts; if (simplifiedResult) { return this.mapDefinitionInfo(definitions, project); } - else { - return definitions; - } + return definitions.map(Session.mapToOriginalLocation); }; Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; @@ -111883,18 +114597,34 @@ var ts; textSpan: this.toLocationTextSpan(definitionAndBoundSpan.textSpan, scriptInfo) }; } - return definitionAndBoundSpan; + return __assign({}, definitionAndBoundSpan, { definitions: definitionAndBoundSpan.definitions.map(Session.mapToOriginalLocation) }); }; Session.prototype.mapDefinitionInfo = function (definitions, project) { var _this = this; return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); }); }; + /* + * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in + * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols. + * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a + * set of additional fields, and does the reverse for VS (store the .d.ts location where + * it used to be and stores the .ts location in the additional fields). + */ + Session.mapToOriginalLocation = function (def) { + if (def.originalFileName) { + ts.Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is"); + return __assign({}, def, { fileName: def.originalFileName, textSpan: def.originalTextSpan, targetFileName: def.fileName, targetTextSpan: def.textSpan }); + } + return def; + }; Session.prototype.toFileSpan = function (fileName, textSpan, project) { - var scriptInfo = project.getScriptInfo(fileName); + var ls = project.getLanguageService(); + var start = ls.toLineColumnOffset(fileName, textSpan.start); + var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan)); return { file: fileName, - start: scriptInfo.positionToLineOffset(textSpan.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) + start: { line: start.line + 1, offset: start.character + 1 }, + end: { line: end.line + 1, offset: end.character + 1 } }; }; Session.prototype.getTypeDefinition = function (args) { @@ -111920,9 +114650,7 @@ var ts; return _this.toFileSpan(fileName, textSpan, project); }); } - else { - return implementations; - } + return implementations.map(Session.mapToOriginalLocation); }; Session.prototype.getOccurrences = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; @@ -112238,7 +114966,8 @@ var ts; textSpan: _this.toLocationTextSpan(s.textSpan, scriptInfo_1), hintSpan: _this.toLocationTextSpan(s.hintSpan, scriptInfo_1), bannerText: s.bannerText, - autoCollapse: s.autoCollapse + autoCollapse: s.autoCollapse, + kind: s.kind }); }); } else { @@ -112394,10 +115123,10 @@ var ts; if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name_75 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. - return { name: name_75, kind: kind, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; } }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); } @@ -112783,10 +115512,16 @@ var ts; }; Session.prototype.mapTextChangesToCodeEditsUsingScriptinfo = function (textChanges, scriptInfo) { var _this = this; - return { - fileName: textChanges.fileName, - textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) - }; + ts.Debug.assert(!!textChanges.isNewFile === !scriptInfo); + if (scriptInfo) { + return { + fileName: textChanges.fileName, + textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }; + } + else { + return this.convertNewFileTextChangeToCodeEdit(textChanges); + } }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { @@ -112795,6 +115530,12 @@ var ts; newText: change.newText ? change.newText : "" }; }; + Session.prototype.convertNewFileTextChangeToCodeEdit = function (textChanges) { + ts.Debug.assert(textChanges.textChanges.length === 1); + var change = ts.first(textChanges.textChanges); + ts.Debug.assert(change.span.start === 0 && change.span.length === 0); + return { fileName: textChanges.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] }; + }; Session.prototype.getBraceMatching = function (args, simplifiedResult) { var _this = this; var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -113727,5 +116468,3 @@ var ts; }()); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); - -//# sourceMappingURL=tsserverlibrary.js.map diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index d54eff0acbd..b449fc853c6 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -337,32 +337,36 @@ declare namespace ts { EnumMember = 272, SourceFile = 273, Bundle = 274, - JSDocTypeExpression = 275, - JSDocAllType = 276, - JSDocUnknownType = 277, - JSDocNullableType = 278, - JSDocNonNullableType = 279, - JSDocOptionalType = 280, - JSDocFunctionType = 281, - JSDocVariadicType = 282, - JSDocComment = 283, - JSDocTypeLiteral = 284, - JSDocTag = 285, - JSDocAugmentsTag = 286, - JSDocClassTag = 287, - JSDocParameterTag = 288, - JSDocReturnTag = 289, - JSDocTypeTag = 290, - JSDocTemplateTag = 291, - JSDocTypedefTag = 292, - JSDocPropertyTag = 293, - SyntaxList = 294, - NotEmittedStatement = 295, - PartiallyEmittedExpression = 296, - CommaListExpression = 297, - MergeDeclarationMarker = 298, - EndOfDeclarationMarker = 299, - Count = 300, + UnparsedSource = 275, + InputFiles = 276, + JSDocTypeExpression = 277, + JSDocAllType = 278, + JSDocUnknownType = 279, + JSDocNullableType = 280, + JSDocNonNullableType = 281, + JSDocOptionalType = 282, + JSDocFunctionType = 283, + JSDocVariadicType = 284, + JSDocComment = 285, + JSDocTypeLiteral = 286, + JSDocSignature = 287, + JSDocTag = 288, + JSDocAugmentsTag = 289, + JSDocClassTag = 290, + JSDocCallbackTag = 291, + JSDocParameterTag = 292, + JSDocReturnTag = 293, + JSDocTypeTag = 294, + JSDocTemplateTag = 295, + JSDocTypedefTag = 296, + JSDocPropertyTag = 297, + SyntaxList = 298, + NotEmittedStatement = 299, + PartiallyEmittedExpression = 300, + CommaListExpression = 301, + MergeDeclarationMarker = 302, + EndOfDeclarationMarker = 303, + Count = 304, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -388,10 +392,10 @@ declare namespace ts { FirstBinaryOperator = 27, LastBinaryOperator = 70, FirstNode = 145, - FirstJSDocNode = 275, - LastJSDocNode = 293, - FirstJSDocTagNode = 285, - LastJSDocTagNode = 293 + FirstJSDocNode = 277, + LastJSDocNode = 297, + FirstJSDocTagNode = 288, + LastJSDocTagNode = 297 } enum NodeFlags { None = 0, @@ -415,6 +419,7 @@ declare namespace ts { ThisNodeOrAnySubNodesHasError = 131072, HasAggregatedChildData = 262144, JSDoc = 2097152, + JsonFile = 16777216, BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, @@ -1149,7 +1154,7 @@ declare namespace ts { kind: SyntaxKind.NotEmittedStatement; } /** - * A list of comma-seperated expressions. This node is only created by transformations. + * A list of comma-separated expressions. This node is only created by transformations. */ interface CommaListExpression extends Expression { kind: SyntaxKind.CommaListExpression; @@ -1277,7 +1282,7 @@ declare namespace ts { block: Block; } type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; + type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; @@ -1534,6 +1539,19 @@ declare namespace ts { name?: Identifier; typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; } + interface JSDocCallbackTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocCallbackTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression: JSDocSignature; + } + interface JSDocSignature extends JSDocType, Declaration { + kind: SyntaxKind.JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + type: JSDocReturnTag | undefined; + } interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; @@ -1644,12 +1662,32 @@ declare namespace ts { } interface Bundle extends Node { kind: SyntaxKind.Bundle; + prepends: ReadonlyArray; sourceFiles: ReadonlyArray; } + interface InputFiles extends Node { + kind: SyntaxKind.InputFiles; + javascriptText: string; + declarationText: string; + } + interface UnparsedSource extends Node { + kind: SyntaxKind.UnparsedSource; + text: string; + } interface JsonSourceFile extends SourceFile { - jsonObject?: ObjectLiteralExpression; + statements: NodeArray; + } + interface TsConfigSourceFile extends JsonSourceFile { extendedSourceFiles?: string[]; } + interface JsonMinusNumericLiteral extends PrefixUnaryExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: SyntaxKind.MinusToken; + operand: NumericLiteral; + } + interface JsonObjectExpressionStatement extends ExpressionStatement { + expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral; + } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; getSourceFile(fileName: string): SourceFile | undefined; @@ -1705,12 +1743,19 @@ declare namespace ts { */ getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; + getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + } + interface ResolvedProjectReference { + commandLine: ParsedCommandLine; + sourceFile: SourceFile; } interface CustomTransformers { - /** Custom transformers to evaluate before built-in transformations. */ + /** Custom transformers to evaluate before built-in .js transformations. */ before?: TransformerFactory[]; - /** Custom transformers to evaluate after built-in transformations. */ + /** Custom transformers to evaluate after built-in .js transformations. */ after?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .d.ts transformations. */ + afterDeclarations?: TransformerFactory[]; } interface SourceMapSpan { /** Line number in the .js file. */ @@ -1853,7 +1898,9 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + GenerateNamesForShadowedTypeParams = 4, UseStructuralFallback = 8, + ForbidIndexedAccessSymbolReferences = 16, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, UseOnlyExternalAliasing = 128, @@ -2217,6 +2264,7 @@ declare namespace ts { objectType: Type; indexType: Type; constraint?: Type; + simplified?: Type; } type TypeVariable = TypeParameter | IndexedAccessType; interface IndexType extends InstantiableType { @@ -2251,7 +2299,7 @@ declare namespace ts { Construct = 1 } interface Signature { - declaration?: SignatureDeclaration; + declaration?: SignatureDeclaration | JSDocSignature; typeParameters?: TypeParameter[]; parameters: Symbol[]; } @@ -2274,7 +2322,9 @@ declare namespace ts { AlwaysStrict = 64, PriorityImpliesCombination = 28 } - interface JsFileExtensionInfo { + /** @deprecated Use FileExtensionInfo instead. */ + type JsFileExtensionInfo = FileExtensionInfo; + interface FileExtensionInfo { extension: string; isMixedContent: boolean; scriptKind?: ScriptKind; @@ -2322,7 +2372,17 @@ declare namespace ts { interface PluginImport { name: string; } - type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined; + interface ProjectReference { + /** A normalized path on disk */ + path: string; + /** The path as the user originally wrote it */ + originalPath?: string; + /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ + prepend?: boolean; + /** True if it is intended that this reference form a circularity */ + circular?: boolean; + } + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -2378,6 +2438,7 @@ declare namespace ts { project?: string; reactNamespace?: string; jsxFactory?: string; + composite?: boolean; removeComments?: boolean; rootDir?: string; rootDirs?: string[]; @@ -2393,11 +2454,12 @@ declare namespace ts { suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; traceResolution?: boolean; + resolveJsonModule?: boolean; types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; esModuleInterop?: boolean; - [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; + [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; } interface TypeAcquisition { enableAutoDiscovery?: boolean; @@ -2437,7 +2499,12 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, - JSON = 6 + JSON = 6, + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + Deferred = 7 } enum ScriptTarget { ES3 = 0, @@ -2447,6 +2514,7 @@ declare namespace ts { ES2017 = 4, ES2018 = 5, ESNext = 6, + JSON = 100, Latest = 6 } enum LanguageVariant { @@ -2458,6 +2526,7 @@ declare namespace ts { options: CompilerOptions; typeAcquisition?: TypeAcquisition; fileNames: string[]; + projectReferences?: ReadonlyArray; raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; @@ -2469,8 +2538,17 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; + projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } + interface CreateProgramOptions { + rootNames: ReadonlyArray; + options: CompilerOptions; + projectReferences?: ReadonlyArray; + host?: CompilerHost; + oldProgram?: Program; + configFileParsingDiagnostics?: ReadonlyArray; + } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2561,6 +2639,7 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; + readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files @@ -2918,10 +2997,11 @@ declare namespace ts { readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** - * This should be cryptographically secure. * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) */ createHash?(data: string): string; + /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */ + createSHA256Hash?(data: string): string; getMemoryUsage?(): number; exit(exitCode?: number): void; realpath?(path: string): string; @@ -3298,6 +3378,8 @@ declare namespace ts { function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; + function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag; + function isJSDocSignature(node: Node): node is JSDocSignature; } declare namespace ts { /** @@ -3423,6 +3505,8 @@ declare namespace ts { function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; + function createStringLiteral(text: string): StringLiteral; + function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ @@ -3727,8 +3811,10 @@ declare namespace ts { function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; function createCommaList(elements: ReadonlyArray): CommaListExpression; function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; - function createBundle(sourceFiles: ReadonlyArray): Bundle; - function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle; + function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createUnparsedSourceFile(text: string): UnparsedSource; + function createInputFiles(javascript: string, declaration: string): InputFiles; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression; function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression; @@ -3792,6 +3878,7 @@ declare namespace ts { function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function moveSyntheticComments(node: T, original: Node): T; /** * Gets the constant value to emit for an expression. */ @@ -3935,6 +4022,7 @@ declare namespace ts { * @param configFileParsingDiagnostics - error during config file parsing * @returns A 'Program' object. */ + function createProgram(createProgramOptions: CreateProgramOptions): Program; function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; } declare namespace ts { @@ -4074,7 +4162,6 @@ declare namespace ts { function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; } declare namespace ts { - type DiagnosticReporter = (diagnostic: Diagnostic) => void; type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; @@ -4137,15 +4224,6 @@ declare namespace ts { /** Compiler options */ options: CompilerOptions; } - /** - * Reports config file diagnostics - */ - interface ConfigFileDiagnosticsReporter { - /** - * Reports unrecoverable error when parsing config file - */ - onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; - } /** * Host to create watch with config file */ @@ -4192,6 +4270,26 @@ declare namespace ts { } declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors + */ + interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter { + getCurrentDirectory(): string; + } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4213,7 +4311,7 @@ declare namespace ts { * Read tsconfig.json file * @param fileName The path to the config file */ - function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile; + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile; /** * Convert the json syntax tree into the json value */ @@ -4225,7 +4323,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; /** * Parse the contents of a config file (tsconfig.json). * @param jsonNode The contents of the config file to parse @@ -4233,7 +4331,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -4252,7 +4350,7 @@ declare namespace ts { getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; getFullStart(): number; getEnd(): number; - getWidth(sourceFile?: SourceFile): number; + getWidth(sourceFile?: SourceFileLike): number; getFullWidth(): number; getLeadingTriviaWidth(sourceFile?: SourceFile): number; getFullText(sourceFile?: SourceFile): string; @@ -4364,6 +4462,7 @@ declare namespace ts { getScriptKind?(fileName: string): ScriptKind; getScriptVersion(fileName: string): string; getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; + getProjectReferences?(): ReadonlyArray | undefined; getLocalizedDiagnosticMessages?(): any; getCancellationToken?(): HostCancellationToken; getCurrentDirectory(): string; @@ -4378,6 +4477,7 @@ declare namespace ts { fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getDirectories?(directoryName: string): string[]; /** @@ -4393,6 +4493,7 @@ declare namespace ts { readonly includeCompletionsForModuleExports?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly allowTextChangesInNewFiles?: boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -4441,6 +4542,7 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; + toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; @@ -4465,9 +4567,10 @@ declare namespace ts { fileName: string; } type OrganizeImportsScope = CombinedCodeFixScope; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; interface GetCompletionsAtPositionOptions extends UserPreferences { /** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */ - triggerCharacter?: string; + triggerCharacter?: CompletionsTriggerCharacter; /** @deprecated Use includeCompletionsForModuleExports */ includeExternalModuleExports?: boolean; /** @deprecated Use includeCompletionsWithInsertText */ @@ -4534,6 +4637,7 @@ declare namespace ts { interface FileTextChanges { fileName: string; textChanges: TextChange[]; + isNewFile?: boolean; } interface CodeAction { /** Description of the code action to display in the UI of the editor */ @@ -4620,6 +4724,12 @@ declare namespace ts { interface DocumentSpan { textSpan: TextSpan; fileName: string; + /** + * If the span represents a location that was remapped (e.g. via a .d.ts.map file), + * then the original filename and span will be specified here + */ + originalTextSpan?: TextSpan; + originalFileName?: string; } interface RenameLocation extends DocumentSpan { } @@ -4717,9 +4827,7 @@ declare namespace ts { insertSpaceBeforeTypeAnnotation?: boolean; indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } - interface DefinitionInfo { - fileName: string; - textSpan: TextSpan; + interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; containerKind: ScriptElementKind; @@ -4865,6 +4973,20 @@ declare namespace ts { * the 'Collapse to Definitions' command is invoked. */ autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + enum OutliningSpanKind { + /** Single or multi-line comments */ + Comment = "comment", + /** Sections marked by '// #region' and '// #endregion' comments */ + Region = "region", + /** Declarations and expressions */ + Code = "code", + /** Contiguous blocks of import declarations */ + Imports = "imports" } enum OutputFileType { JavaScript = 0, @@ -4988,7 +5110,9 @@ declare namespace ts { /** * */ - jsxAttribute = "JSX attribute" + jsxAttribute = "JSX attribute", + /** String literal */ + string = "string" } enum ScriptElementKindModifier { none = "", diff --git a/lib/typescript.js b/lib/typescript.js index 86c2e32ef0e..5a20323ef59 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -350,38 +350,42 @@ var ts; // Top-level nodes SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile"; SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 275] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 276] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 277] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 278] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 279] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 280] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 281] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 282] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 283] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 284] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 285] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 286] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 287] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 288] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 289] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 290] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 291] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 292] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 293] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 294] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 295] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 296] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 297] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 298] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 299] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 300] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 301] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 302] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 303] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 304] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -408,10 +412,10 @@ var ts; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 277] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 297] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 288] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 297] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -451,6 +455,7 @@ var ts; NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; @@ -513,10 +518,9 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; // Flags - GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; @@ -591,9 +595,9 @@ var ts; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; @@ -885,6 +889,8 @@ var ts; TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType"; TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive"; /* @internal */ + TypeFlags[TypeFlags["UnionOfUnitTypes"] = 268435456] = "UnionOfUnitTypes"; + /* @internal */ TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; @@ -920,6 +926,8 @@ var ts; TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit"; /* @internal */ + TypeFlags[TypeFlags["NotUnit"] = 8374815] = "NotUnit"; + /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening"; /* @internal */ TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags"; @@ -1072,6 +1080,11 @@ var ts; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -1082,6 +1095,7 @@ var ts; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; @@ -1894,8 +1908,8 @@ var ts; } ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ - function findIndex(array, predicate) { - for (var i = 0; i < array.length; i++) { + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -1903,6 +1917,15 @@ var ts; return -1; } ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; /** * Returns the first truthy result of `callback`, or else fails. * This is like `forEach`, but never returns undefined. @@ -2255,6 +2278,24 @@ var ts; return false; } ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; function concatenate(array1, array2) { if (!some(array2)) return array1; @@ -2498,6 +2539,23 @@ var ts; return to; } ts.addRange = addRange; + /** + * Appends a range of value to begin of an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + function prependRange(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + to.unshift.apply(to, from); + return to; + } + ts.prependRange = prependRange; /** * @return Whether the value was added. */ @@ -2747,17 +2805,18 @@ var ts; } ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { + var _a; var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { result.push(map ? map(value) : value); } return result; - var _b; } ts.arrayFrom = arrayFrom; function forEachEntry(map, callback) { + var _a; var iterator = map.entries(); - for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { var key = pair[0], value = pair[1]; var result = callback(value, key); if (result) { @@ -2765,19 +2824,18 @@ var ts; } } return undefined; - var _b; } ts.forEachEntry = forEachEntry; function forEachKey(map, callback) { + var _a; var iterator = map.keys(); - for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { var result = callback(key); if (result) { return result; } } return undefined; - var _b; } ts.forEachKey = forEachKey; function copyEntries(source, target) { @@ -3334,11 +3392,11 @@ var ts; comparer(a[key], b[key]); } ts.compareProperties = compareProperties; - function getDiagnosticFileName(diagnostic) { - return diagnostic.file ? diagnostic.file.fileName : undefined; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; } function compareDiagnostics(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -3370,106 +3428,6 @@ var ts; // We still have one chain remaining. The shorter chain should come first. return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; } - function normalizeSlashes(path) { - return path.replace(/\\/g, "/"); - } - ts.normalizeSlashes = normalizeSlashes; - /** - * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") - */ - function getRootLength(path) { - if (path.charCodeAt(0) === 47 /* slash */) { - if (path.charCodeAt(1) !== 47 /* slash */) - return 1; - var p1 = path.indexOf("/", 2); - if (p1 < 0) - return 2; - var p2 = path.indexOf("/", p1 + 1); - if (p2 < 0) - return p1 + 1; - return p2 + 1; - } - if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) - return 3; - } - // Per RFC 1738 'file' URI schema has the shape file:/// - // if is omitted then it is assumed that host value is 'localhost', - // however slash after the omitted is not removed. - // file:///folder1/file1 - this is a correct URI - // file://folder2/file2 - this is an incorrect URI - if (path.lastIndexOf("file:///", 0) === 0) { - return "file:///".length; - } - var idx = path.indexOf("://"); - if (idx !== -1) { - return idx + "://".length; - } - return 0; - } - ts.getRootLength = getRootLength; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var directorySeparatorCharCode = 47 /* slash */; - function getNormalizedParts(normalizedSlashedPath, rootLength) { - var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); - var normalized = []; - for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { - var part = parts_1[_i]; - if (part !== ".") { - if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { - normalized.pop(); - } - else { - // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, - // e.g. "path//file.ts". Drop these before re-joining the parts. - if (part) { - normalized.push(part); - } - } - } - } - return normalized; - } - function normalizePath(path) { - return normalizePathAndParts(path).path; - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - var root = path.substr(0, rootLength); - var parts = getNormalizedParts(path, rootLength); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - /** A path ending with '/' refers to a directory only, never a file. */ - function pathEndsWithDirectorySeparator(path) { - return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; - } - ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; - function getDirectoryPath(path) { - return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function isUrl(path) { - return path && !isRootedDiskPath(path) && stringContains(path, "://"); - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0 /* ES3 */; } @@ -3501,6 +3459,10 @@ var ts; : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; } @@ -3521,202 +3483,455 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + // + // Paths + // + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ function isRootedDiskPath(path) { - return path && getRootLength(path) !== 0; + return getEncodedRootLength(path) > 0; } ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); } ts.convertToRelativePath = convertToRelativePath; - function normalizedPathComponents(path, rootLength) { - var normalizedParts = getNormalizedParts(path, rootLength); - return [path.substr(0, rootLength)].concat(normalizedParts); + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); } - function getNormalizedPathComponents(path, currentDirectory) { - path = normalizeSlashes(path); + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); var rootLength = getRootLength(path); - if (rootLength === 0) { - // If the path is not rooted it is relative to current directory - path = combinePaths(normalizeSlashes(currentDirectory), path); - rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); } - return normalizedPathComponents(path, rootLength); + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); } ts.getNormalizedPathComponents = getNormalizedPathComponents; function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); } ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getNormalizedPathFromPathComponents(pathComponents) { - if (pathComponents && pathComponents.length) { - return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); - } + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + if (pathComponents.length === 1) + return root; + return root + pathComponents.slice(1).join(ts.directorySeparator); } - ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; - function getNormalizedPathComponentsOfUrl(url) { - // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ - // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] - var urlLength = url.length; - // Initial root length is http:// part - var rootLength = url.indexOf("://") + "://".length; - while (rootLength < urlLength) { - // Consume all immediate slashes in the protocol - // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// - if (url.charCodeAt(rootLength) === 47 /* slash */) { - rootLength++; - } - else { - // non slash character means we continue proceeding to next component of root search + ts.getPathFromPathComponents = getPathFromPathComponents; + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) break; - } } - // there are no parts after http:// just return current string as the pathComponent - if (rootLength === urlLength) { - return [url]; + if (start === 0) { + return toComponents; } - // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) - var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); - if (indexOfNextSlash !== -1) { - // Found the "/" after the website.com so the root is length of http://www.website.com/ - // and get components after the root normally like any other folder components - rootLength = indexOfNextSlash + 1; - return normalizedPathComponents(url, rootLength); - } - else { - // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" - // eg. if url passed in was http://website.com we want to use root as [http://website.com/] - // so that other path manipulations will be correct and it can be merged with relative paths correctly - return [url + ts.directorySeparator]; + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); } + return [""].concat(relative, components); } - function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { - if (isUrl(pathOrUrl)) { - return getNormalizedPathComponentsOfUrl(pathOrUrl); - } - else { - return getNormalizedPathComponents(pathOrUrl, currentDirectory); - } + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] - directoryComponents.pop(); + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; } - // Find the component that differs - var joinStartIndex; - for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { - break; - } - } - // Get the relative path - if (joinStartIndex) { - var relativePath = ""; - var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); - for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (directoryComponents[joinStartIndex] !== "") { - relativePath = relativePath + ".." + ts.directorySeparator; - } - } - return relativePath + relativePathComponents.join(ts.directorySeparator); - } - // Cant find the relative path, get the absolute path - var absolutePath = getNormalizedPathFromPathComponents(pathComponents); - if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { - absolutePath = "file:///" + absolutePath; - } - return absolutePath; + return getPathFromPathComponents(pathComponents); } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function getRelativePath(path, directoryPath, getCanonicalFileName) { - var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ensurePathIsRelative(relativePath); + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path; } - ts.getRelativePath = getRelativePath; - function ensurePathIsRelative(path) { - return !pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsRelative = ensurePathIsRelative; - function getBaseFileName(path) { - if (path === undefined) { - return undefined; - } - var i = path.lastIndexOf(ts.directorySeparator); - return i < 0 ? path : path.substring(i + 1); + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; } ts.getBaseFileName = getBaseFileName; - function combinePaths(path1, path2) { - if (!(path1 && path1.length)) - return path2; - if (!(path2 && path2.length)) - return path1; - if (getRootLength(path2) !== 0) - return path2; - if (path1.charAt(path1.length - 1) === ts.directorySeparator) - return path1 + path2; - return path1 + ts.directorySeparator + path2; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; } ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function removeTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) === ts.directorySeparator) { + if (hasTrailingDirectorySeparator(path)) { return path.substr(0, path.length - 1); } return path; } ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; function ensureTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) !== ts.directorySeparator) { + if (!hasTrailingDirectorySeparator(path)) { return path + ts.directorySeparator; } return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - function comparePaths(a, b, currentDirectory, ignoreCase) { + function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0 /* EqualTo */; if (a === undefined) return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; - a = removeTrailingDirectorySeparator(a); - b = removeTrailingDirectorySeparator(b); - var aComponents = getNormalizedPathComponents(a, currentDirectory); - var bComponents = getNormalizedPathComponents(b, currentDirectory); + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - var comparer = getStringComparer(ignoreCase); for (var i = 0; i < sharedLength; i++) { - var result = comparer(aComponents[i], bComponents[i]); + var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); if (result !== 0 /* EqualTo */) { return result; } } return compareValues(aComponents.length, bComponents.length); } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, getStringComparer(ignoreCase)); + } ts.comparePaths = comparePaths; function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } if (parent === undefined || child === undefined) return false; if (parent === child) return true; - parent = removeTrailingDirectorySeparator(parent); - child = removeTrailingDirectorySeparator(child); - if (parent === child) - return true; - var parentComponents = getNormalizedPathComponents(parent, currentDirectory); - var childComponents = getNormalizedPathComponents(child, currentDirectory); + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); if (childComponents.length < parentComponents.length) { return false; } - var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; + var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer; if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } @@ -4050,13 +4265,17 @@ var ts; ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { - var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { - return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; + function isJavaScriptLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } function hasJavaScriptFileExtension(fileName) { return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } @@ -4128,7 +4347,7 @@ var ts; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */]; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { var ext = extensionsToRemove_1[_i]; @@ -4149,9 +4368,14 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return (removeFileExtension(path) + newExtension); + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -4437,6 +4661,10 @@ var ts; return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } ts.extensionIsTypeScript = extensionIsTypeScript; + function resolutionExtensionIsTypeScriptOrJson(ext) { + return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -4457,14 +4685,34 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - function getAnyExtensionFromPath(path) { + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive); + } var baseFileName = getBaseFileName(path); var extensionIndex = baseFileName.lastIndexOf("."); if (extensionIndex >= 0) { return baseFileName.substring(extensionIndex); } + return ""; } ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -4566,12 +4814,12 @@ var ts; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { + var _a; return _a = {}, _a[PollingInterval.Low] = levels.Low, _a[PollingInterval.Medium] = levels.Medium, _a[PollingInterval.High] = levels.High, _a; - var _a; } var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); @@ -4936,6 +5184,7 @@ var ts; readDirectory: readDirectory, getModifiedTime: getModifiedTime, createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, getMemoryUsage: function () { if (global.gc) { global.gc(); @@ -5374,6 +5623,11 @@ var ts; hash.update(data); return hash.digest("hex"); } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -5685,7 +5939,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -6162,6 +6416,7 @@ var ts; Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -6345,6 +6600,17 @@ var ts; Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -6443,6 +6709,7 @@ var ts; Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -6506,6 +6773,12 @@ var ts; Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), }; })(ts || (ts = {})); var ts; @@ -8256,11 +8529,10 @@ var ts; } } function scanJSDocToken() { + startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; } - startPos = pos; - tokenPos = pos; var ch = text.charCodeAt(pos); pos++; switch (ch) { @@ -8666,7 +8938,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 294 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 298 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8868,12 +9140,12 @@ var ts; case 159 /* IndexSignature */: case 162 /* FunctionType */: case 163 /* ConstructorType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: case 235 /* InterfaceDeclaration */: case 236 /* TypeAliasDeclaration */: - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: case 233 /* FunctionDeclaration */: case 153 /* MethodDeclaration */: case 154 /* Constructor */: @@ -8881,6 +9153,9 @@ var ts; case 156 /* SetAccessor */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + case 287 /* JSDocSignature */: return true; default: ts.assertTypeIsNever(node); @@ -8903,6 +9178,12 @@ var ts; case 243 /* ImportDeclaration */: case 242 /* ImportEqualsDeclaration */: case 213 /* VariableStatement */: + case 234 /* ClassDeclaration */: + case 233 /* FunctionDeclaration */: + case 238 /* ModuleDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 237 /* EnumDeclaration */: return true; default: return false; @@ -8916,13 +9197,7 @@ var ts; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { - var current = node.parent; - while (current) { - if (isBlockScope(current, current.parent)) { - return current; - } - current = current.parent; - } + return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; // Return display name of an identifier @@ -9040,6 +9315,8 @@ var ts; case 155 /* GetAccessor */: case 156 /* SetAccessor */: case 236 /* TypeAliasDeclaration */: + case 151 /* PropertyDeclaration */: + case 150 /* PropertySignature */: errorNode = node.name; break; case 192 /* ArrowFunction */: @@ -9070,6 +9347,10 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; + } + ts.isJsonSourceFile = isJsonSourceFile; function isConstEnumDeclaration(node) { return node.kind === 237 /* EnumDeclaration */ && isConst(node); } @@ -9409,6 +9690,23 @@ var ts; }); } ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.isObjectLiteralExpression(expression) && expression; + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral && + ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -9786,6 +10084,10 @@ var ts; return node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJsonFile(node) { + return node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { return node && !!(node.flags & 2097152 /* JSDoc */); } @@ -10010,6 +10312,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243 /* ImportDeclaration */: case 249 /* ExportDeclaration */: @@ -10019,12 +10325,13 @@ var ts; case 186 /* CallExpression */: return node.parent; case 177 /* LiteralType */: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243 /* ImportDeclaration */: @@ -10073,12 +10380,20 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 281 /* JSDocFunctionType */ && + return node.kind === 283 /* JSDocFunctionType */ && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 296 /* JSDocTypedefTag */ || node.kind === 291 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && @@ -10100,6 +10415,8 @@ var ts; return v && v.initializer; case 151 /* PropertyDeclaration */: return node.initializer; + case 269 /* PropertyAssignment */: + return node.initializer; } } function getSingleVariableOfVariableStatement(node) { @@ -10113,9 +10430,9 @@ var ts; node.body.kind === 238 /* ModuleDeclaration */ && node.body; } - function getJSDocCommentsAndTags(node) { + function getJSDocCommentsAndTags(hostNode) { var result; - getJSDocCommentsAndTagsWorker(node); + getJSDocCommentsAndTagsWorker(hostNode); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; @@ -10130,8 +10447,7 @@ var ts; // * @returns {number} // */ // var x = function(name) { return name.length; } - if (parent.parent && - (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { + if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) { getJSDocCommentsAndTagsWorker(parent.parent); } if (parent.parent && parent.parent.parent && @@ -10140,8 +10456,8 @@ var ts; getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } - if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || - ts.isBinaryExpression(parent) && getSpecialPropertyAssignmentKind(parent) !== 0 /* None */ || + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */ || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */ || node.kind === 184 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 215 /* ExpressionStatement */) { getJSDocCommentsAndTagsWorker(parent); } @@ -10149,7 +10465,7 @@ var ts; if (node.kind === 148 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -10176,7 +10492,10 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - var host = getJSDocHost(node); + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || @@ -10185,19 +10504,9 @@ var ts; host; return decl && ts.isFunctionLike(decl) ? decl : undefined; } - ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; function getJSDocHost(node) { - while (node.parent.kind === 284 /* JSDocTypeLiteral */) { - if (node.parent.parent.kind === 292 /* JSDocTypedefTag */) { - node = node.parent.parent; - } - else { - // node.parent.parent is a type expression, child of a parameter type - node = node.parent.parent.parent; - } - } - ts.Debug.assert(node.parent.kind === 283 /* JSDocComment */); - return node.parent.parent; + return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent; } ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { @@ -10212,7 +10521,8 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282 /* JSDocVariadicType */; + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || type && type.kind === 284 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -10354,8 +10664,14 @@ var ts; if (ts.isDeclaration(name.parent)) { return name.parent.name === name; } - var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + else if (ts.isQualifiedName(name.parent)) { + var tag = name.parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + } + else { + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + } default: return false; } @@ -10735,7 +11051,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: return 0; case 203 /* SpreadElement */: return 1; @@ -11064,8 +11380,8 @@ var ts; }; } ts.createTextWriter = createTextWriter; - function getResolvedExternalModuleName(host, file) { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { @@ -11079,12 +11395,13 @@ var ts; /** * Resolves a local path to a path which is absolute to the base of the emit */ - function getExternalModuleNameFromPath(host, fileName) { + function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.removeFileExtension(relativePath); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { @@ -11178,7 +11495,8 @@ var ts; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { - if (signature.parameters.length) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { var thisParameter = signature.parameters[0]; if (parameterIsThisKeyword(thisParameter)) { return thisParameter; @@ -11263,6 +11581,9 @@ var ts; * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { + if (ts.isJSDocSignature(node)) { + return node.type && node.type.typeExpression && node.type.typeExpression.type; + } return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; @@ -11271,12 +11592,27 @@ var ts; * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ function getEffectiveTypeParameterDeclarations(node) { - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 285 /* JSDocComment */); + var templateTags = ts.flatMap(ts.filter(node.parent.tags, ts.isJSDocTemplateTag), function (tag) { return tag.typeParameters; }); + var templateTagNodes = templateTags; + templateTagNodes.pos = templateTagNodes.length > 0 ? ts.first(templateTagNodes).pos : node.pos; + templateTagNodes.end = templateTagNodes.length > 0 ? ts.last(templateTagNodes).end : node.end; + templateTagNodes.hasTrailingComma = false; + return templateTagNodes; + } + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; + // template tags are only available when a typedef isn't already using them + var tag = ts.find(ts.getJSDocTags(node), function (tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + }); + return (tag && tag.typeParameters) || ts.emptyArray; } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** @@ -12664,8 +13000,8 @@ var ts; break; case 71 /* Identifier */: return declaration; - case 293 /* JSDocPropertyTag */: - case 288 /* JSDocParameterTag */: { + case 297 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: { var name = declaration.name; if (name.kind === 145 /* QualifiedName */) { return name.right; @@ -12684,7 +13020,9 @@ var ts; return undefined; } } - case 292 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + return declaration.name; + case 296 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); case 248 /* ExportAssignment */: { var expression = declaration.expression; @@ -12817,7 +13155,9 @@ var ts; var tags = node.jsDocCache; // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); } return tags; } @@ -12935,6 +13275,11 @@ var ts; return node.kind === 159 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 156 /* SetAccessor */ || node.kind === 155 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { return node.kind === 160 /* TypePredicate */; @@ -13063,7 +13408,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296 /* PartiallyEmittedExpression */) { + while (node.kind === 300 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -13419,81 +13764,89 @@ var ts; ts.isBundle = isBundle; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 275 /* JSDocTypeExpression */; + return node.kind === 277 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 276 /* JSDocAllType */; + return node.kind === 278 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 277 /* JSDocUnknownType */; + return node.kind === 279 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 278 /* JSDocNullableType */; + return node.kind === 280 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 279 /* JSDocNonNullableType */; + return node.kind === 281 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 280 /* JSDocOptionalType */; + return node.kind === 282 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 281 /* JSDocFunctionType */; + return node.kind === 283 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 282 /* JSDocVariadicType */; + return node.kind === 284 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 283 /* JSDocComment */; + return node.kind === 285 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 286 /* JSDocAugmentsTag */; + return node.kind === 289 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 287 /* JSDocClassTag */; + return node.kind === 290 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { - return node.kind === 288 /* JSDocParameterTag */; + return node.kind === 292 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 289 /* JSDocReturnTag */; + return node.kind === 293 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 290 /* JSDocTypeTag */; + return node.kind === 294 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 291 /* JSDocTemplateTag */; + return node.kind === 295 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 292 /* JSDocTypedefTag */; + return node.kind === 296 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 293 /* JSDocPropertyTag */; + return node.kind === 297 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 293 /* JSDocPropertyTag */ || node.kind === 288 /* JSDocParameterTag */; + return node.kind === 297 /* JSDocPropertyTag */ || node.kind === 292 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 284 /* JSDocTypeLiteral */; + return node.kind === 286 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 291 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 287 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); // Node tests // @@ -13502,7 +13855,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 294 /* SyntaxList */; + return n.kind === 298 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13647,10 +14000,11 @@ var ts; switch (kind) { case 152 /* MethodSignature */: case 157 /* CallSignature */: + case 287 /* JSDocSignature */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: case 162 /* FunctionType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: case 163 /* ConstructorType */: return true; default: @@ -13734,13 +14088,13 @@ var ts; || kind === 95 /* NullKeyword */ || kind === 131 /* NeverKeyword */ || kind === 206 /* ExpressionWithTypeArguments */ - || kind === 276 /* JSDocAllType */ - || kind === 277 /* JSDocUnknownType */ - || kind === 278 /* JSDocNullableType */ - || kind === 279 /* JSDocNonNullableType */ - || kind === 280 /* JSDocOptionalType */ - || kind === 281 /* JSDocFunctionType */ - || kind === 282 /* JSDocVariadicType */; + || kind === 278 /* JSDocAllType */ + || kind === 279 /* JSDocUnknownType */ + || kind === 280 /* JSDocNullableType */ + || kind === 281 /* JSDocNonNullableType */ + || kind === 282 /* JSDocOptionalType */ + || kind === 283 /* JSDocFunctionType */ + || kind === 284 /* JSDocVariadicType */; } /** * Node test that determines whether a node is a valid type node. @@ -13962,8 +14316,8 @@ var ts; case 203 /* SpreadElement */: case 207 /* AsExpression */: case 205 /* OmittedExpression */: - case 297 /* CommaListExpression */: - case 296 /* PartiallyEmittedExpression */: + case 301 /* CommaListExpression */: + case 300 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13977,12 +14331,12 @@ var ts; ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 296 /* PartiallyEmittedExpression */; + return node.kind === 300 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 295 /* NotEmittedStatement */; + return node.kind === 299 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -14093,7 +14447,9 @@ var ts; || kind === 236 /* TypeAliasDeclaration */ || kind === 147 /* TypeParameter */ || kind === 231 /* VariableDeclaration */ - || kind === 292 /* JSDocTypedefTag */; + || kind === 296 /* JSDocTypedefTag */ + || kind === 291 /* JSDocCallbackTag */ + || kind === 297 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { return kind === 233 /* FunctionDeclaration */ @@ -14128,14 +14484,14 @@ var ts; || kind === 213 /* VariableStatement */ || kind === 218 /* WhileStatement */ || kind === 225 /* WithStatement */ - || kind === 295 /* NotEmittedStatement */ - || kind === 299 /* EndOfDeclarationMarker */ - || kind === 298 /* MergeDeclarationMarker */; + || kind === 299 /* NotEmittedStatement */ + || kind === 303 /* EndOfDeclarationMarker */ + || kind === 302 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 147 /* TypeParameter */) { - return node.parent.kind !== 291 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 295 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -14230,18 +14586,18 @@ var ts; /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 275 /* FirstJSDocNode */ && node.kind <= 293 /* LastJSDocNode */; + return node.kind >= 277 /* FirstJSDocNode */ && node.kind <= 297 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 283 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node); + return node.kind === 285 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 285 /* FirstJSDocTagNode */ && node.kind <= 293 /* LastJSDocTagNode */; + return node.kind >= 288 /* FirstJSDocTagNode */ && node.kind <= 297 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -14292,12 +14648,12 @@ var ts; case 231 /* VariableDeclaration */: case 233 /* FunctionDeclaration */: case 236 /* TypeAliasDeclaration */: - case 275 /* JSDocTypeExpression */: - case 278 /* JSDocNullableType */: - case 279 /* JSDocNonNullableType */: - case 280 /* JSDocOptionalType */: - case 281 /* JSDocFunctionType */: - case 282 /* JSDocVariadicType */: + case 277 /* JSDocTypeExpression */: + case 280 /* JSDocNullableType */: + case 281 /* JSDocNonNullableType */: + case 282 /* JSDocOptionalType */: + case 283 /* JSDocFunctionType */: + case 284 /* JSDocVariadicType */: return true; } return false; @@ -14787,7 +15143,7 @@ var ts; return visitNode(cbNode, node.expression); case 252 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 254 /* JsxElement */: return visitNode(cbNode, node.openingElement) || @@ -14814,23 +15170,23 @@ var ts; visitNode(cbNode, node.expression); case 257 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 275 /* JSDocTypeExpression */: + case 277 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 279 /* JSDocNonNullableType */: + case 281 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 278 /* JSDocNullableType */: + case 280 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 280 /* JSDocOptionalType */: + case 282 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 283 /* JSDocComment */: + case 285 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 288 /* JSDocParameterTag */: - case 293 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: + case 297 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -14839,17 +15195,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 289 /* JSDocReturnTag */: + case 293 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 290 /* JSDocTypeTag */: + case 294 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 286 /* JSDocAugmentsTag */: + case 289 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 292 /* JSDocTypedefTag */: + case 296 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 275 /* JSDocTypeExpression */) { + node.typeExpression.kind === 277 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -14857,7 +15213,16 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 284 /* JSDocTypeLiteral */: + case 291 /* JSDocCallbackTag */: + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 287 /* JSDocSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 286 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -14865,7 +15230,7 @@ var ts; } } return; - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -14873,7 +15238,13 @@ var ts; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; @@ -15033,6 +15404,13 @@ var ts; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + return result_1; + } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); @@ -15050,25 +15428,57 @@ var ts; return isInvalid ? entityName : undefined; } Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function parseJsonText(fileName, sourceText) { - initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); // Set source file so that errors will be reported with this file name sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); - var result = sourceFile; // Prime the scanner. nextToken(); + var pos = getNodePos(); if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); sourceFile.endOfFileToken = parseTokenNode(); } - else if (token() === 17 /* OpenBraceToken */ || - lookAhead(function () { return token() === 9 /* StringLiteral */; })) { - result.jsonObject = parseObjectLiteralExpression(); + else { + var statement = createNode(215 /* ExpressionStatement */); + switch (token()) { + case 21 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 38 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); } - else { - parseExpected(17 /* OpenBraceToken */); + if (setParentNodes) { + fixupParentReferences(sourceFile); } sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; clearState(); return result; } @@ -15092,9 +15502,11 @@ var ts; switch (scriptKind) { case 1 /* JS */: case 2 /* JSX */: - case 6 /* JSON */: contextFlags = 65536 /* JavaScriptFile */; break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; default: contextFlags = 0 /* None */; break; @@ -16340,9 +16752,9 @@ var ts; return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(276 /* JSDocAllType */); + var result = createNode(278 /* JSDocAllType */); if (postFixEquals) { - return createJSDocPostfixType(280 /* JSDocOptionalType */, result); + return createJSDocPostfixType(282 /* JSDocOptionalType */, result); } else { nextToken(); @@ -16350,7 +16762,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(279 /* JSDocNonNullableType */); + var result = createNode(281 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -16374,18 +16786,18 @@ var ts; token() === 29 /* GreaterThanToken */ || token() === 58 /* EqualsToken */ || token() === 49 /* BarToken */) { - var result = createNode(277 /* JSDocUnknownType */, pos); + var result = createNode(279 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(278 /* JSDocNullableType */, pos); + var result = createNode(280 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(281 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(283 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); @@ -16407,12 +16819,12 @@ var ts; var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseType(); if (dotdotdot) { - var variadic = createNode(282 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(284 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } if (token() === 58 /* EqualsToken */) { - return createJSDocPostfixType(280 /* JSDocOptionalType */, type); + return createJSDocPostfixType(282 /* JSDocOptionalType */, type); } return type; } @@ -16496,15 +16908,19 @@ var ts; node.initializer = parseInitializer(); return finishNode(node); } + /** + * @returns If return type parsing succeeds + */ function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */)); - } - function parseReturnType(returnToken, isType) { - return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + return signature.type !== undefined; + } + return true; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36 /* EqualsGreaterThanToken */) { @@ -16783,6 +17199,9 @@ var ts; var node = createNode(172 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); + if (!node.type) { + return undefined; + } parseExpected(20 /* CloseParenToken */); return finishNode(node); } @@ -16791,7 +17210,12 @@ var ts; if (kind === 163 /* ConstructorType */) { parseExpected(94 /* NewKeyword */); } - fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + if (!fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */ | (sourceFile.languageVariant === 1 /* JSX */ ? 8 /* RequireCompleteParameterList */ : 0), node)) { + return undefined; + } + if (!node.parameters) { + return undefined; + } return finishNode(node); } function parseKeywordAndNoDot() { @@ -16947,14 +17371,14 @@ var ts; while (!scanner.hasPrecedingLineBreak()) { switch (token()) { case 51 /* ExclamationToken */: - type = createJSDocPostfixType(279 /* JSDocNonNullableType */, type); + type = createJSDocPostfixType(281 /* JSDocNonNullableType */, type); break; case 55 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createJSDocPostfixType(278 /* JSDocNullableType */, type); + type = createJSDocPostfixType(280 /* JSDocNullableType */, type); break; case 21 /* OpenBracketToken */: parseExpected(21 /* OpenBracketToken */); @@ -17518,7 +17942,7 @@ var ts; // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] if (token() === 120 /* AsyncKeyword */) { nextToken(); - // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { return 0 /* False */; @@ -17542,7 +17966,9 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node); + if (!fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node)) { + return undefined; + } // If we couldn't get parameters, we definitely could not parse out an arrow function. if (!node.parameters) { return undefined; @@ -19905,7 +20331,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos()); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -19925,6 +20351,7 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var _a; var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -19942,7 +20369,6 @@ var ts; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; - var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; var JSDocState; @@ -19953,8 +20379,9 @@ var ts; })(JSDocState || (JSDocState = {})); var PropertyLikeParse; (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; @@ -20002,7 +20429,7 @@ var ts; case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); - parseTag(indent); + addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning // for malformed examples like `/** @param {string} x @returns {number} the length */` @@ -20076,12 +20503,29 @@ var ts; } } function createJSDocComment() { - var result = createNode(283 /* JSDocComment */, start); + var result = createNode(285 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { nextJSDocToken(); } @@ -20110,8 +20554,7 @@ var ts; case "arg": case "argument": case "param": - addTag(parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */, indent)); - return; + return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); case "return": case "returns": tag = parseReturnTag(atToken, tagName); @@ -20123,7 +20566,10 @@ var ts; tag = parseTypeTag(atToken, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(atToken, tagName, indent); break; default: tag = parseUnknownTag(atToken, tagName); @@ -20137,8 +20583,11 @@ var ts; // a badly malformed tag should not be added to the list of tags return; } - tag.comment = parseTagComments(indent + tag.end - tag.pos); - addTag(tag); + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; } function parseTagComments(indent) { var comments = []; @@ -20201,12 +20650,15 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { - var result = createNode(285 /* JSDocTag */, atToken.pos); + var result = createNode(288 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } function addTag(tag) { + if (!tag) { + return; + } if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -20257,9 +20709,9 @@ var ts; if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var result = target === 1 /* Parameter */ ? - createNode(288 /* JSDocParameterTag */, atToken.pos) : - createNode(293 /* JSDocPropertyTag */, atToken.pos); + var result = target === 1 /* Property */ ? + createNode(297 /* JSDocPropertyTag */, atToken.pos) : + createNode(292 /* JSDocParameterTag */, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -20279,18 +20731,18 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name, target) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 288 /* JSDocParameterTag */ || child.kind === 293 /* JSDocPropertyTag */) { + if (child.kind === 292 /* JSDocParameterTag */ || child.kind === 297 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; if (typeExpression.type.kind === 166 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; @@ -20301,27 +20753,27 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 293 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(289 /* JSDocReturnTag */, atToken.pos); + var result = createNode(293 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 290 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 294 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(290 /* JSDocTypeTag */, atToken.pos); + var result = createNode(294 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var result = createNode(286 /* JSDocAugmentsTag */, atToken.pos); + var result = createNode(289 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); @@ -20349,32 +20801,23 @@ var ts; return node; } function parseClassTag(atToken, tagName) { - var tag = createNode(287 /* JSDocClassTag */, atToken.pos); + var tag = createNode(290 /* JSDocClassTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); } - function parseTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(292 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(296 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { - // if node is identifier - use it as name - // otherwise use name of the rightmost part that we were able to parse - typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); skipWhitespace(); + typedefTag.comment = parseTagComments(indent); typedefTag.typeExpression = typeExpression; + var end; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; @@ -20382,9 +20825,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 290 /* JSDocTypeTag */) { + if (child.kind === 294 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -20403,23 +20846,68 @@ var ts; typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; } } - return finishNode(typedefTag); - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); - return finishNode(jsDocNamespaceNode); + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { + var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } - if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { - typeNameOrNamespaceName.isInJSDocNamespace = true; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(atToken, tagName, indent) { + var callbackTag = createNode(291 /* JSDocCallbackTag */, atToken.pos); + callbackTag.atToken = atToken; + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var start = scanner.getStartPos(); + var jsdocSignature = createNode(287 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (token() === 57 /* AtToken */) { + nextJSDocToken(); + var tag = parseTag(indent); + if (tag && tag.kind === 293 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; } - return typeNameOrNamespaceName; } } function escapedTextsEqual(a, b) { @@ -20435,7 +20923,7 @@ var ts; return a.escapedText === b.escapedText; } function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(0 /* Property */); + return parseChildParameterOrPropertyTag(1 /* Property */); } function parseChildParameterOrPropertyTag(target, name) { var canParseTag = true; @@ -20445,7 +20933,8 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 288 /* JSDocParameterTag */ && + if (child && child.kind === 292 /* JSDocParameterTag */ && + target !== 4 /* CallbackParameter */ && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -20484,20 +20973,20 @@ var ts; var t; switch (tagName.escapedText) { case "type": - return target === 0 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - t = 0 /* Property */; + t = 1 /* Property */; break; case "arg": case "argument": case "param": - t = 1 /* Parameter */; + t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; default: return false; } - if (target !== t) { + if (!(target & t)) { return false; } var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); @@ -20530,7 +21019,7 @@ var ts; break; } } - var result = createNode(291 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(295 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -20579,7 +21068,7 @@ var ts; var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); var result = createNode(71 /* Identifier */, pos); - result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); return result; @@ -21383,7 +21872,7 @@ var ts; var thisParentContainer; // Container one level up var blockScopeContainer; var lastContainer; - var delayedTypedefs; + var delayedTypeAliases; var seenThisKeyword; // state used by control flow analysis var currentFlow; @@ -21441,7 +21930,7 @@ var ts; thisParentContainer = undefined; blockScopeContainer = undefined; lastContainer = undefined; - delayedTypedefs = undefined; + delayedTypeAliases = undefined; seenThisKeyword = false; currentFlow = undefined; currentBreakTarget = undefined; @@ -21515,6 +22004,7 @@ var ts; return "__constructor" /* Constructor */; case 162 /* FunctionType */: case 157 /* CallSignature */: + case 287 /* JSDocSignature */: return "__call" /* Call */; case 163 /* ConstructorType */: case 158 /* ConstructSignature */: @@ -21523,6 +22013,10 @@ var ts; return "__index" /* Index */; case 249 /* ExportDeclaration */: return "__export" /* ExportStar */; + case 273 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; case 199 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { // module.exports = ... @@ -21530,18 +22024,15 @@ var ts; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); case 148 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 281 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 283 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; - case 292 /* JSDocTypedefTag */: - var name_2 = ts.getNameOfJSDocTypedef(node); - return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } } function getDisplayName(node) { @@ -21679,9 +22170,9 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (node.kind === 292 /* JSDocTypedefTag */) + if (ts.isJSDocTypeAlias(node)) ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypedefTag(node)) { + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } @@ -21846,23 +22337,6 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - // Binding of JsDocComment should be done before the current block scope container changes. - // because the scope of JsDocComment should not be affected by whether the current node is a - // container or not. - if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var j = _a[_i]; - bind(j); - } - } - else { - for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { - var j = _c[_b]; - setParentPointers(node, j); - } - } - } if (checkUnreachable(node)) { bindEachChild(node); return; @@ -21928,11 +22402,9 @@ var ts; case 186 /* CallExpression */: bindCallExpressionFlow(node); break; - case 283 /* JSDocComment */: - bindJSDocComment(node); - break; - case 292 /* JSDocTypedefTag */: - bindJSDocTypedefTag(node); + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 273 /* SourceFile */: @@ -21947,6 +22419,7 @@ var ts; bindEachChild(node); break; } + bindJSDoc(node); } function isNarrowingExpression(expr) { switch (expr.kind) { @@ -22548,23 +23021,10 @@ var ts; bindInitializedVariableFlow(node); } } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 292 /* JSDocTypedefTag */) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - // if the node has a fullName "A.B.C", that means symbol "C" was already bound - // when we visit "fullName"; so when we visit the name "C" as the next child of - // the jsDocTypedefTag, we should skip binding it. - if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { - return; - } - bind(n); - }); + function bindJSDocTypeAlias(node) { + if (node.fullName) { + setParentPointers(node, node.fullName); + } } function bindCallExpressionFlow(node) { // If the target of the call expression is a function expression or arrow function we have @@ -22596,7 +23056,7 @@ var ts; case 237 /* EnumDeclaration */: case 183 /* ObjectLiteralExpression */: case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: + case 286 /* JSDocTypeLiteral */: case 262 /* JsxAttributes */: return 1 /* IsContainer */; case 235 /* InterfaceDeclaration */: @@ -22618,7 +23078,8 @@ var ts; case 155 /* GetAccessor */: case 156 /* SetAccessor */: case 157 /* CallSignature */: - case 281 /* JSDocFunctionType */: + case 287 /* JSDocSignature */: + case 283 /* JSDocFunctionType */: case 162 /* FunctionType */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: @@ -22680,7 +23141,7 @@ var ts; case 237 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: + case 286 /* JSDocTypeLiteral */: case 183 /* ObjectLiteralExpression */: case 235 /* InterfaceDeclaration */: case 262 /* JsxAttributes */: @@ -22694,6 +23155,7 @@ var ts; case 163 /* ConstructorType */: case 157 /* CallSignature */: case 158 /* ConstructSignature */: + case 287 /* JSDocSignature */: case 159 /* IndexSignature */: case 153 /* MethodDeclaration */: case 152 /* MethodSignature */: @@ -22703,7 +23165,9 @@ var ts; case 233 /* FunctionDeclaration */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: case 236 /* TypeAliasDeclaration */: case 176 /* MappedType */: // All the children of these container types are never visible through another @@ -22878,22 +23342,35 @@ var ts; bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); } function delayedBindJSDocTypedefTag() { - if (!delayedTypedefs) { + if (!delayedTypeAliases) { return; } var saveContainer = container; var saveLastContainer = lastContainer; var saveBlockScopeContainer = blockScopeContainer; var saveParent = parent; - for (var _i = 0, delayedTypedefs_1 = delayedTypedefs; _i < delayedTypedefs_1.length; _i++) { - var delay = delayedTypedefs_1[_i]; - (container = delay.container, lastContainer = delay.lastContainer, blockScopeContainer = delay.blockScopeContainer, parent = delay.parent); - bindBlockScopedDeclaration(delay.typedef, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } } container = saveContainer; lastContainer = saveLastContainer; blockScopeContainer = saveBlockScopeContainer; parent = saveParent; + currentFlow = saveCurrentFlow; } // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized // check for reserved words used as identifiers in strict mode code. @@ -23045,8 +23522,6 @@ var ts; // Here the current node is "foo", which is a container, but the scope of "MyType" should // not be inside "foo". Therefore we always bind @typedef before bind the parent node, // and skip binding this tag later when binding all the other jsdoc tags. - if (ts.isInJavaScriptFile(node)) - bindJSDocTypedefTagIfAny(node); // First we bind declaration nodes to a symbol if possible. We'll both create a symbol // and then potentially add the symbol to an appropriate symbol table. Possible // destination symbol tables are: @@ -23077,25 +23552,22 @@ var ts; } else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + bindJSDoc(node); } inStrictMode = saveInStrictMode; } - function bindJSDocTypedefTagIfAny(node) { - if (!ts.hasJSDocNodes(node)) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 292 /* JSDocTypedefTag */) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); } } } @@ -23130,7 +23602,7 @@ var ts; // current "blockScopeContainer" needs to be set to its immediate namespace parent. if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 292 /* JSDocTypedefTag */) { + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); @@ -23232,11 +23704,12 @@ var ts; case 156 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); case 162 /* FunctionType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: + case 287 /* JSDocSignature */: case 163 /* ConstructorType */: return bindFunctionOrConstructorType(node); case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: + case 286 /* JSDocTypeLiteral */: case 176 /* MappedType */: return bindAnonymousTypeWorker(node); case 183 /* ObjectLiteralExpression */: @@ -23292,24 +23765,23 @@ var ts; // falls through case 239 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 288 /* JSDocParameterTag */: - if (node.parent.kind !== 284 /* JSDocTypeLiteral */) { + case 292 /* JSDocParameterTag */: + if (node.parent.kind === 287 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 286 /* JSDocTypeLiteral */) { break; } // falls through - case 293 /* JSDocPropertyTag */: + case 297 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 280 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 282 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 292 /* JSDocTypedefTag */: { - var fullName = node.fullName; - if (!fullName || fullName.kind === 71 /* Identifier */) { - (delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node, container: container, lastContainer: lastContainer, blockScopeContainer: blockScopeContainer, parent: parent }); - } - break; - } + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } function bindPropertyWorker(node) { @@ -23323,6 +23795,13 @@ var ts; if (ts.isExternalModule(file)) { bindSourceFileAsExternalModule(); } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } } function bindSourceFileAsExternalModule() { bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); @@ -23662,6 +24141,9 @@ var ts; } } function bindParameter(node) { + if (node.kind === 292 /* JSDocParameterTag */ && container.kind !== 287 /* JSDocSignature */) { + return; + } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) @@ -23720,24 +24202,30 @@ var ts; : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } function getInferTypeContainer(node) { - while (node) { - var parent_2 = node.parent; - if (parent_2 && parent_2.kind === 170 /* ConditionalType */ && parent_2.extendsType === node) { - return parent_2; - } - node = parent_2; - } - return undefined; + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; } function bindTypeParameter(node) { - if (node.parent.kind === 171 /* InferType */) { - var container_1 = getInferTypeContainer(node.parent); + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); if (container_1) { if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 171 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); } @@ -23999,7 +24487,7 @@ var ts; else { // A ClassDeclaration is ES6 syntax. transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is + // A class with a parameter property assignment, property initializer, computed property name, or decorator is // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. @@ -24136,9 +24624,9 @@ var ts; function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; - // If the PropertyDeclaration has an initializer, we need to inform its ancestor + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. - if (node.initializer) { + if (node.initializer || ts.isComputedPropertyName(node.name)) { transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -24362,7 +24850,7 @@ var ts; break; case 189 /* TypeAssertionExpression */: case 207 /* AsExpression */: - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; @@ -24634,7 +25122,7 @@ var ts; return 940049729 /* BindingPatternExcludes */; case 189 /* TypeAssertionExpression */: case 207 /* AsExpression */: - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: case 190 /* ParenthesizedExpression */: case 97 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; @@ -24652,7 +25140,7 @@ var ts; */ function setParentPointers(parent, child) { child.parent = parent; - ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); } })(ts || (ts = {})); /** @internal */ @@ -24850,7 +25338,8 @@ var ts; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { @@ -24894,7 +25383,13 @@ var ts; function readJson(path, host) { try { var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; } catch (e) { // gracefully handle if readFile fails or returns not JSON @@ -25425,7 +25920,11 @@ var ts; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + var result = jsOnly ? + tryResolve(Extensions.JavaScript) : + (tryResolve(Extensions.TypeScript) || + tryResolve(Extensions.JavaScript) || + (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); @@ -25480,7 +25979,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); if (!directoryProbablyExists(parentOfCandidate, state.host)) { @@ -25565,6 +26064,10 @@ var ts; * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (extensions === Extensions.Json) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -25585,9 +26088,9 @@ var ts; function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + var directory_1 = ts.getDirectoryPath(candidate); + if (directory_1) { + onlyRecordFailures = !directoryProbablyExists(directory_1, state.host); } } switch (extensions) { @@ -25597,6 +26100,8 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.Json: + return tryExtension(".json" /* Json */); } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); @@ -25649,8 +26154,11 @@ var ts; } else { var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string") { - subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */; + if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { + var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; } else { subModuleName = "index.d.ts"; @@ -25683,9 +26191,18 @@ var ts; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); if (!file) { - return undefined; + if (extensions === Extensions.TypeScript) { + // When resolving typescript modules, try resolving using main field as well + file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + if (!file) { + return undefined; + } + } + else { + return undefined; + } } var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); @@ -25718,6 +26235,8 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.Json: + return extension === ".json" /* Json */; case Extensions.TypeScript: return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; case Extensions.DtsOnly: @@ -25788,7 +26307,7 @@ var ts; if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript) { + if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { @@ -26213,7 +26732,7 @@ var ts; checkSourceFile(file); var diagnostics = []; ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); - checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { if (!unusedIsError(kind)) { diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } @@ -26283,6 +26802,7 @@ var ts; var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); @@ -26327,8 +26847,6 @@ var ts; var deferredGlobalExtractSymbol; var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name - var potentiallyUnusedIdentifiers; // Potentially unused identifiers in the source file currently being checked. - var seenPotentiallyUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -26639,17 +27157,17 @@ var ts; } function getJsxNamespace(location) { if (location) { - var file = ts.getSourceFileOfNode(location); - if (file) { - if (file.localJsxNamespace) { - return file.localJsxNamespace; + var file_1 = ts.getSourceFileOfNode(location); + if (file_1) { + if (file_1.localJsxNamespace) { + return file_1.localJsxNamespace; } - var jsxPragma = file.pragmas.get("jsx"); + var jsxPragma = file_1.pragmas.get("jsx"); if (jsxPragma) { var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; - file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); - if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file_1.localJsxFactory) { + return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText; } } } @@ -26761,6 +27279,8 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* JSContainer */) { + var targetValueDeclaration = target.valueDeclaration; + ts.Debug.assert(!!(target.flags & 33554432 /* Transient */)); // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums @@ -26786,7 +27306,12 @@ var ts; } if ((source.flags | target.flags) & 67108864 /* JSContainer */) { var sourceInitializer = ts.getJSInitializerSymbol(source); - var targetInitializer = ts.getJSInitializerSymbol(target); + var init = ts.getDeclaredJavascriptInitializer(targetValueDeclaration) || ts.getAssignedJavascriptInitializer(targetValueDeclaration); + var targetInitializer = init && init.symbol ? init.symbol : target; + if (!(targetInitializer.flags & 33554432 /* Transient */)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } if (sourceInitializer !== source || targetInitializer !== target) { mergeSymbol(targetInitializer, sourceInitializer); } @@ -27070,7 +27595,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 283 /* JSDocComment */) { + if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 285 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -27269,6 +27794,12 @@ var ts; location = location.parent; } break; + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + lastLocation = location; + location = ts.getJSDocHost(location).parent; + continue; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -27384,9 +27915,11 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (decl.kind === 147 /* TypeParameter */ && parent === container) { - return true; + if (decl.kind === 147 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + } } } return false; @@ -27597,8 +28130,8 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); - var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + var file_2 = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file_2, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -27850,7 +28383,7 @@ var ts; var symbol; if (name.kind === 71 /* Identifier */) { var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSPrototype(name, meaning) : undefined; + var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -27859,40 +28392,40 @@ var ts; else if (name.kind === 145 /* QualifiedName */ || name.kind === 184 /* PropertyAccessExpression */) { var left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); - if (!namespace || ts.nodeIsMissing(right)) { + var namespace_1 = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace_1 || ts.nodeIsMissing(right)) { return undefined; } - else if (namespace === unknownSymbol) { - return namespace; + else if (namespace_1 === unknownSymbol) { + return namespace_1; } if (ts.isInJavaScriptFile(name)) { - var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); + var initializer = ts.getDeclaredJavascriptInitializer(namespace_1.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace_1.valueDeclaration); if (initializer) { - namespace = getSymbolOfNode(initializer); + namespace_1 = getSymbolOfNode(initializer); } // Currently, IIFEs may not have a symbol and we don't know about their contents. Give up in this case. - if (!namespace) { + if (!namespace_1) { return undefined; } - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + if (namespace_1.valueDeclaration && + ts.isVariableDeclaration(namespace_1.valueDeclaration) && + namespace_1.valueDeclaration.initializer && + isCommonJsRequire(namespace_1.valueDeclaration.initializer)) { + var moduleName = namespace_1.valueDeclaration.initializer.arguments[0]; var moduleSym = resolveExternalModuleName(moduleName, moduleName); if (moduleSym) { var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; + namespace_1 = resolvedModuleSymbol; } } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getSymbol(getExportsOfSymbol(namespace_1), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace_1), ts.declarationNameToString(right)); } return undefined; } @@ -27904,24 +28437,37 @@ var ts; return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } /** - * For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSPrototype(name, meaning) { - if (isJSDocTypeReference(name.parent) && ts.isJSDocTag(name.parent.parent.parent)) { - var host_1 = ts.getJSDocHost(name.parent.parent.parent); - if (ts.isExpressionStatement(host_1) && - ts.isBinaryExpression(host_1.expression) && - ts.getSpecialPropertyAssignmentKind(host_1.expression) === 3 /* PrototypeProperty */) { - var symbol = getSymbolOfNode(host_1.expression.left); - if (symbol) { - var secondaryLocation = symbol.parent.valueDeclaration; - return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); - } + function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } + function getJSSpecialAssignmentLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + var symbol = getSymbolOfNode(host.expression.left); + return symbol && symbol.parent.valueDeclaration; + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -27970,7 +28516,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -27982,7 +28528,22 @@ var ts; return undefined; } if (moduleNotFoundError) { - // report errors only if it was requested + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } if (resolutionDiagnostic) { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } @@ -28429,7 +28990,7 @@ var ts; * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { + if (symbol && enclosingDeclaration) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { @@ -28446,6 +29007,14 @@ var ts; } return hasAccessibleDeclarations; } + else { + if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. // It could be a qualified symbol and hence verify the path // e.g.: @@ -28511,6 +29080,11 @@ var ts; isDeclarationVisible(declaration.parent.parent.parent)) { return addVisibleAlias(declaration, declaration.parent.parent); } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } // Declaration is not visible return false; } @@ -28678,7 +29252,7 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined, + visitedSymbols: undefined, inferTypeParameters: undefined }; } @@ -28770,16 +29344,25 @@ var ts; } if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { - return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 32768 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { - var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name, typeArgumentNodes); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); } if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) { var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types; @@ -28828,14 +29411,26 @@ var ts; ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; + var id; if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); if (isJavaScriptConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; @@ -28847,7 +29442,7 @@ var ts; shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, 67216319 /* Value */); } - else if (ts.contains(context.symbolStack, symbol)) { + else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { @@ -28861,19 +29456,13 @@ var ts; else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.symbolStack) { - context.symbolStack = []; - } - var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - return createTypeNodeFromObjectType(type); - } - else { - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + if (!context.visitedSymbols) { + context.visitedSymbols = ts.createMap(); } + context.visitedSymbols.set(id, true); + var result = createTypeNodeFromObjectType(type); + context.visitedSymbols.delete(id); + return result; } } else { @@ -28890,7 +29479,7 @@ var ts; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed } } @@ -28922,11 +29511,6 @@ var ts; var typeLiteralNode = ts.createTypeLiteralNode(members); return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } - function symbolToTypeReferenceName(symbol) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); - return entityName; - } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { @@ -28959,7 +29543,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = void 0; + var resultType = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -28973,55 +29557,65 @@ var ts; // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); - var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); - var namePart = symbolToTypeReferenceName(parent); - (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); - } - else { - qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); - } + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } } } - var entityName = void 0; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } var typeArgumentNodes = void 0; if (typeArguments.length > 0) { var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } - if (typeArgumentNodes) { - var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; - lastIdentifier.typeArguments = undefined; - } - return ts.createTypeReferenceNode(entityName, typeArgumentNodes); + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } } - function addToQualifiedNameMissingRightIdentifier(left, right) { - ts.Debug.assert(left.right === undefined); - if (right.kind === 71 /* Identifier */) { - left.right = right; - return left; + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; } - var rightPart = right; - while (rightPart.left.kind !== 71 /* Identifier */) { - rightPart = rightPart.left; + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; } - left.right = rightPart.left; - rightPart.left = left; - return right; + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; @@ -29168,32 +29762,47 @@ var ts; } return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148 /* Parameter */); - ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 292 /* JSDocParameterTag */); + } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; + var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - cloneBindingName(parameterDeclaration.name) : + parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 145 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -29213,7 +29822,7 @@ var ts; } } } - function lookupSymbolChain(symbol, context, meaning) { + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; @@ -29249,7 +29858,7 @@ var ts; // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; @@ -29281,22 +29890,54 @@ var ts; } return typeParameterNodes; } - function symbolToTypeNode(symbol, context, meaning) { - var chain = lookupSymbolChain(symbol, context, meaning); + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module context.flags |= 16777216 /* InInitialEntityName */; var rootName = getNameOfSymbolAsWritten(chain[0], context); context.flags ^= 16777216 /* InInitialEntityName */; var isTypeOf = meaning === 67216319 /* Value */; if (ambientModuleSymbolRegex.test(rootName)) { // module is root, must use `ImportTypeNode` - var nonRootParts = chain.length > 1 ? createEntityNameFromSymbolChain(chain, chain.length - 1, 1) : undefined; - var typeParameterNodes = lookupTypeParameterNodes(chain, 0, context); - return ts.createImportTypeNode(ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))), nonRootParts, typeParameterNodes, isTypeOf); + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))); + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } } - var entityName = createEntityNameFromSymbolChain(chain, chain.length - 1, 0); - return isTypeOf ? ts.createTypeQueryNode(entityName) : ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); - function createEntityNameFromSymbolChain(chain, index, stopper) { - var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; @@ -29305,9 +29946,27 @@ var ts; if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); identifier.symbol = symbol; - return index > stopper ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1, stopper), identifier) : identifier; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; } } function symbolToName(symbol, context, meaning, expectsIdentifier) { @@ -29456,6 +30115,24 @@ var ts; return "default"; } if (symbol.declarations && symbol.declarations.length) { + if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { + var file_3 = ts.getDeclarationOfKind(symbol, 273 /* SourceFile */); + if (!file_3 || !context.tracker.moduleResolverHost) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl); + } + } + } + // ambient module, just use declaration/symbol name (fallthrough) + } + else { + return "\"" + ts.getResolvedExternalModuleName(context.tracker.moduleResolverHost, file_3, ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration))) + "\""; + } + } var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { @@ -29497,6 +30174,11 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); case 181 /* BindingElement */: return isDeclarationVisible(node.parent.parent); case 231 /* VariableDeclaration */: @@ -30209,7 +30891,7 @@ var ts; if (symbol.flags & 4194304 /* Prototype */) { return links.type = getTypeOfPrototypeProperty(symbol); } - // CommonsJS require/module/exports all have type any. + // CommonsJS require and module both have type any. if (symbol === requireSymbol || symbol === moduleSymbol) { return links.type = anyType; } @@ -30219,6 +30901,10 @@ var ts; return links.type = anyType; } // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } if (declaration.kind === 248 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } @@ -30239,7 +30925,7 @@ var ts; declaration.kind === 184 /* PropertyAccessExpression */ && declaration.parent.kind === 199 /* BinaryExpression */) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else if (ts.isJSDocPropertyTag(declaration) + else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) || ts.isIdentifier(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) @@ -30510,13 +31196,15 @@ var ts; case 152 /* MethodSignature */: case 162 /* FunctionType */: case 163 /* ConstructorType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: case 233 /* FunctionDeclaration */: case 153 /* MethodDeclaration */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: case 236 /* TypeAliasDeclaration */: - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: case 176 /* MappedType */: case 170 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); @@ -30526,7 +31214,7 @@ var ts; else if (node.kind === 170 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 234 /* ClassDeclaration */ || node.kind === 204 /* ClassExpression */ || node.kind === 235 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; @@ -30545,13 +31233,12 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 235 /* InterfaceDeclaration */ || node.kind === 234 /* ClassDeclaration */ || - node.kind === 204 /* ClassExpression */ || node.kind === 236 /* TypeAliasDeclaration */) { + if (node.kind === 235 /* InterfaceDeclaration */ || + node.kind === 234 /* ClassDeclaration */ || + node.kind === 204 /* ClassExpression */ || + ts.isTypeAlias(node)) { var declaration = node; - var typeParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - if (typeParameters) { - result = appendTypeParameters(result, typeParameters); - } + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); } } return result; @@ -30828,9 +31515,9 @@ var ts; return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 292 /* JSDocTypedefTag */ || d.kind === 236 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 236 /* TypeAliasDeclaration */; }); - var typeNode = declaration.kind === 292 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { @@ -31035,7 +31722,7 @@ var ts; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && - (!typeParameters || typeParameters.every(isThislessTypeParameter)); + typeParameters.every(isThislessTypeParameter); } /** * Returns true if the class or interface member given by the symbol is free of "this" references. The @@ -31084,6 +31771,9 @@ var ts; var symbol = type.symbol; var members = getMembersOfSymbol(symbol); type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); @@ -31213,9 +31903,9 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_3 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); } lateSymbol.nameType = type; @@ -31644,10 +32334,8 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var constraintDeclaration = type.declaration.typeParameter.constraint; var include = keyofStringsOnly ? 32 /* StringLiteral */ : 1120 /* StringOrNumberLiteralOrUnique */; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; @@ -31720,15 +32408,21 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : unknownType); } + function getConstraintDeclarationForMappedType(type) { + return type.declaration.typeParameter.constraint; + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); + return constraintDeclaration.kind === 174 /* TypeOperator */ && + constraintDeclaration.operator === 128 /* KeyOfKeyword */; + } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); } else { // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, @@ -31889,9 +32583,9 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(type.checkType); + var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); if (constraint) { - var mapper = createTypeMapper([type.root.checkType], [constraint]); + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 16384 /* Never */)) { return instantiated; @@ -32278,9 +32972,10 @@ var ts; // type checking functions). function getTypeParametersFromDeclaration(declaration) { var result; - ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); - }); + } return result; } function symbolsToArray(symbols) { @@ -32295,10 +32990,10 @@ var ts; function isJSDocOptionalParameter(node) { return ts.isInJavaScriptFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 280 /* JSDocOptionalType */ + node.type && node.type.kind === 282 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 280 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -32310,7 +33005,7 @@ var ts; return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -32327,6 +33022,13 @@ var ts; } return false; } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */; + } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); @@ -32384,7 +33086,7 @@ var ts; for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); @@ -32415,6 +33117,7 @@ var ts; for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); @@ -32427,12 +33130,13 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 177 /* LiteralType */) { + if (type && type.kind === 177 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || isUntypedSignatureInJSFile || isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { @@ -32466,7 +33170,7 @@ var ts; * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` */ function maybeAddJsSyntheticRestParameter(declaration, parameters) { - if (!containsArgumentsReference(declaration)) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { return false; } var lastParam = ts.lastOrUndefined(declaration.parameters); @@ -32859,7 +33563,7 @@ var ts; var isJs = ts.isInJavaScriptFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 286 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && node.parent.kind !== 289 /* JSDocAugmentsTag */; var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -33010,7 +33714,7 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node)) { + while (node && !ts.isStatement(node) && node.kind !== 285 /* JSDocComment */) { var parent = node.parent; if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); @@ -33460,7 +34164,7 @@ var ts; includes & 4096 /* Undefined */ ? includes & 16777216 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 8374815 /* NotUnit */ ? 0 : 268435456 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -33497,7 +34201,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -33508,7 +34212,7 @@ var ts; var type = unionTypes.get(id); if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */); - type = createType(131072 /* Union */ | propagatedFlags); + type = createType(131072 /* Union */ | propagatedFlags | unionOfUnitTypes); unionTypes.set(id, type); type.types = types; /* @@ -33525,7 +34229,8 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -33574,6 +34279,31 @@ var ts; } } } + // When intersecting unions of unit types we can simply intersect based on type identity. + // Here we remove all unions of unit types from the given list and replace them with a + // a single union containing an intersection of the unit types. + function intersectUnionsOfUnitTypes(types) { + var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 268435456 /* UnionOfUnitTypes */) !== 0; }); + var unionType = types[unionIndex]; + var intersection = unionType.types; + var i = types.length - 1; + var _loop_5 = function () { + var t = types[i]; + if (t.flags & 268435456 /* UnionOfUnitTypes */) { + intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + ts.orderedRemoveItemAt(types, i); + } + i--; + }; + while (i > unionIndex) { + _loop_5(); + } + if (intersection === unionType.types) { + return false; + } + types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 268435456 /* UnionOfUnitTypes */); + return true; + } // We normalize combinations of intersection and union types based on the distributive property of the '&' // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection // types with union type constituents into equivalent union types with intersection type constituents and @@ -33608,6 +34338,12 @@ var ts; return typeSet[0]; } if (includes & 131072 /* Union */) { + if (includes & 268435456 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 131072 /* Union */) !== 0; }); @@ -33629,7 +34365,8 @@ var ts; function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -33806,6 +34543,10 @@ var ts; // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // the type itself if no transformation is possible. function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; var objectType = type.objectType; if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) { // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or @@ -33824,7 +34565,7 @@ var ts; regularTypes.push(t); } } - return getUnionType([ + return type.simplified = getUnionType([ getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), getIntersectionType(stringIndexTypes) ]); @@ -33835,7 +34576,7 @@ var ts; // eventually anyway, but it easier to reason about. if (ts.some(objectType.types, isMappedTypeToNever)) { var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); } } // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper @@ -33843,15 +34584,15 @@ var ts; // construct the type Box. We do not further simplify the result because mapped types can be recursive // and we might never terminate. if (isGenericMappedType(objectType)) { - return substituteIndexedMappedType(objectType, type); + return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { - return substituteIndexedMappedType(constraint, type); + return type.simplified = substituteIndexedMappedType(constraint, type); } } - return type; + return type.simplified = type; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); @@ -33916,7 +34657,7 @@ var ts; var type = createObjectType(32 /* Mapped */, node.symbol); type.declaration = node; type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); links.resolvedType = type; // Eagerly resolve the constraint type which forces an error if the constraint type circularly // references itself through one or more type aliases. @@ -33939,14 +34680,14 @@ var ts; var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */); var combinedMapper; if (root.inferTypeParameters) { - var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + var context_1 = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); if (!isDeferred) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + inferTypes(context_1.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); } - combinedMapper = combineTypeMappers(mapper, context); + combinedMapper = combineTypeMappers(mapper, context_1); } if (!isDeferred) { // Return union of trueType and falseType for 'any' since it matches anything @@ -34017,7 +34758,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var checkType = getTypeFromTypeNode(node.checkType); - var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); var root = { @@ -34030,7 +34772,7 @@ var ts; inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, - aliasSymbol: getAliasSymbolForTypeNode(node), + aliasSymbol: aliasSymbol, aliasTypeArguments: aliasTypeArguments }; links.resolvedType = getConditionalType(root, /*mapper*/ undefined); @@ -34129,7 +34871,7 @@ var ts; else { var type = createObjectType(16 /* Anonymous */, node.symbol); type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { type = createArrayType(type); } @@ -34139,10 +34881,9 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 236 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); + function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } /** @@ -34321,8 +35062,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119 /* AnyKeyword */: - case 276 /* JSDocAllType */: - case 277 /* JSDocUnknownType */: + case 278 /* JSDocAllType */: + case 279 /* JSDocUnknownType */: return anyType; case 137 /* StringKeyword */: return stringType; @@ -34363,21 +35104,22 @@ var ts; return getTypeFromUnionTypeNode(node); case 169 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 278 /* JSDocNullableType */: + case 280 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 280 /* JSDocOptionalType */: + case 282 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); case 172 /* ParenthesizedType */: - case 279 /* JSDocNonNullableType */: - case 275 /* JSDocTypeExpression */: + case 281 /* JSDocNonNullableType */: + case 277 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); case 162 /* FunctionType */: case 163 /* ConstructorType */: case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: - case 281 /* JSDocFunctionType */: + case 286 /* JSDocTypeLiteral */: + case 283 /* JSDocFunctionType */: + case 287 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 174 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); @@ -34567,6 +35309,15 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; + if (ts.isInJavaScriptFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); if (isJavaScriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); @@ -34608,8 +35359,8 @@ var ts; // between the node and the type parameter declaration, if the node contains actual references to the // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_2 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_2; })) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_3; })) { return ts.forEachChild(node, containsReference); } } @@ -35459,7 +36210,7 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { + var _loop_6 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -35496,7 +36247,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_5(prop); + var state_3 = _loop_6(prop); if (typeof state_3 === "object") return state_3.value; } @@ -35802,16 +36553,19 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || constraint.flags & 1 /* Any */) { + if (!constraint || (source.flags & 32768 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~134217728 /* NonPrimitive */))) { errorInfo = saveErrorInfo; return result; } } - else if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var instantiated = getTypeWithThisArgument(constraint, source); + if (result = isRelatedTo(instantiated, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else if (source.flags & 524288 /* Index */) { @@ -35939,10 +36693,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_1; - if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -38049,7 +38803,7 @@ var ts; if (type.flags & 131072 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 268435456 /* UnionOfUnitTypes */); } return f(type) ? type : neverType; } @@ -39285,7 +40039,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 281 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 283 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -39721,7 +40475,7 @@ var ts; // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? - getTypeOfExpression(left, /*cache*/ true) : type; + getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; @@ -40000,8 +40754,18 @@ var ts; return unknownType; } } - if (context.typeArguments) { - signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + var links = getNodeLinks(context); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(valueType); + var cachedResolved = links.resolvedSignatures.get(cacheKey); + if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { + signatures = cachedResolved; + } + else if (!cachedResolved) { + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); } return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); } @@ -40312,7 +41076,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 179 /* ObjectBindingPattern */ || contextualType.pattern.kind === 183 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; @@ -40908,6 +41672,37 @@ var ts; } return undefined; } + function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { + var links = getNodeLinks(openingLikeElement); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(elementType); + if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { + return; + } + else if (links.resolvedSignatures.get(cacheKey)) { + return links.resolvedSignatures.get(cacheKey); + } + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(elementType, 0 /* Call */); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + if (reportErrors) { + error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); + } + return; + } + } + // Instantiate in context of source type + var results = instantiateJsxSignatures(openingLikeElement, signatures); + links.resolvedSignatures.set(cacheKey, results); + return results; + } /** * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. * For instance: @@ -40963,19 +41758,10 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(elementType, 1 /* Construct */); - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(elementType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - return unknownType; - } + var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); + if (!ts.length(instantiatedSignatures)) { + return unknownType; } - // Instantiate in context of source type - var instantiatedSignatures = instantiateJsxSignatures(openingLikeElement, signatures); var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. @@ -41199,7 +41985,7 @@ var ts; // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span if (ts.length(openingLikeElement.attributes.properties)) { var reportedError = false; - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (ts.isJsxSpreadAttribute(prop)) return "continue"; var name = ts.idText(prop.name); @@ -41213,7 +41999,7 @@ var ts; }; for (var _b = 0, _c = openingLikeElement.attributes.properties; _b < _c.length; _b++) { var prop = _c[_b]; - _loop_6(prop); + _loop_7(prop); } if (reportedError) { return; @@ -42484,10 +43270,10 @@ var ts; var isDecorator = node.kind === 149 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; - if (!isDecorator && !isJsxOpeningOrSelfClosingElement) { + if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (isTaggedTemplate || node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -43012,28 +43798,6 @@ var ts; */ function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); - return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - } - /** - * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. - * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible - * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. - * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures - */ - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) - if (elementType.flags & 131072 /* Union */) { - var types = elementType.types; - var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); - } - return result; - } var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); @@ -43053,7 +43817,18 @@ var ts; case 256 /* JsxOpeningElement */: case 255 /* JsxSelfClosingElement */: // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; + var exprTypes = checkExpression(node.tagName); + return forEachType(exprTypes, function (exprType) { + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + if (sfcResult && sfcResult !== unknownSignature) { + return sfcResult; + } + var sigs = getInstantiatedJsxSignatures(node, exprType); + if (candidatesOutArray && ts.length(sigs)) { + candidatesOutArray.push.apply(candidatesOutArray, sigs); + } + return ts.length(sigs) ? sigs[0] : unknownSignature; + }) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -43251,8 +44026,8 @@ var ts; if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); - var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + var file_4 = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file_4, originalSymbol, /*dontResolveAlias*/ false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); @@ -43706,7 +44481,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -43940,8 +44715,8 @@ var ts; } if (type.flags & 393216 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -45036,7 +45811,7 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (node.kind !== 159 /* IndexSignature */ && node.kind !== 281 /* JSDocFunctionType */) { + if (node.kind !== 159 /* IndexSignature */ && node.kind !== 283 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -45499,7 +46274,7 @@ var ts; n.parent.kind !== 234 /* ClassDeclaration */ && n.parent.kind !== 204 /* ClassExpression */ && n.flags & 4194304 /* Ambient */) { - if (!(flags & 2 /* Ambient */)) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported flags |= 1 /* Export */; } @@ -45769,8 +46544,9 @@ var ts; switch (d.kind) { case 235 /* InterfaceDeclaration */: case 236 /* TypeAliasDeclaration */: - // A jsdoc typedef is, by definition, a type alias - case 292 /* JSDocTypedefTag */: + // A jsdoc typedef and callback are, by definition, type aliases + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: return 2 /* ExportType */; case 238 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ @@ -45792,10 +46568,10 @@ var ts; case 242 /* ImportEqualsDeclaration */: case 245 /* NamespaceImport */: case 244 /* ImportClause */: - var result_2 = 0 /* None */; + var result_3 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; case 231 /* VariableDeclaration */: case 181 /* BindingElement */: case 233 /* FunctionDeclaration */: @@ -46239,7 +47015,7 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDocTypedefTag(node) { + function checkJSDocTypeAliasTag(node) { if (!node.typeExpression) { // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); @@ -46363,7 +47139,13 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (potentiallyUnusedIdentifiers) { + if (produceDiagnostics) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } // TODO: GH#22580 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); potentiallyUnusedIdentifiers.push(node); @@ -46373,10 +47155,6 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 273 /* SourceFile */: - case 238 /* ModuleDeclaration */: - checkUnusedModuleMembers(node, addDiagnostic); - break; case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); @@ -46385,6 +47163,8 @@ var ts; case 235 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; + case 273 /* SourceFile */: + case 238 /* ModuleDeclaration */: case 212 /* Block */: case 240 /* CaseBlock */: case 219 /* ForStatement */: @@ -46417,33 +47197,6 @@ var ts; } } } - function checkUnusedLocalsAndParameters(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - node.locals.forEach(function (local) { - // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. - // If it's a type parameter merged with a parameter, check if the parameter-side is used. - if (local.flags & 262144 /* TypeParameter */ ? (local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : !local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148 /* Parameter */) { - var parameter = ts.getRootDeclaration(local.valueDeclaration); - var name = ts.getNameOfDeclaration(local.valueDeclaration); - if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } - } - else { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local), addDiagnostic); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { @@ -46453,10 +47206,8 @@ var ts; return; } } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); - } + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -46504,7 +47255,7 @@ var ts; // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304 /* Ambient */) && typeParameters && ts.last(getSymbolOfNode(node).declarations) === node) { + if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { @@ -46513,50 +47264,91 @@ var ts; } } } - function checkUnusedModuleMembers(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. - var unusedImports_1 = ts.createMap(); - node.locals.forEach(function (local) { - if (local.isReferenced || local.exportSymbol) - return; - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isAmbientModule(declaration)) - continue; - if (isImportedDeclaration(declaration)) { - var importClause = importClauseFromImported(declaration); - var key = String(getNodeId(importClause)); - var group_1 = unusedImports_1.get(key); - if (group_1) { - group_1[1].push(declaration); - } - else { - unusedImports_1.set(key, [importClause, [declaration]]); + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + if (parameter) { + var name = ts.getNameOfDeclaration(local.valueDeclaration); + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { + addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); } } - }); - unusedImports_1.forEach(function (_a) { - var importClause = _a[0], unuseds = _a[1]; - var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { - for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { - var unused = unuseds_1[_i]; - errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); - } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } - else if (unuseds.length === 1) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else if (unuseds.length === 1) { + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else { + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } - else { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl))); - } - }); - } + } + else if (bindingElements.length === 1) { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + } + else { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + }); } function isImportedDeclaration(node) { return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */; @@ -47731,7 +48523,7 @@ var ts; var declaration = declarations_6[_i]; // If this declaration has too few or too many type parameters, we report an error var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - var numTypeParameters = ts.length(sourceParameters); + var numTypeParameters = sourceParameters.length; if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; } @@ -47879,7 +48671,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -47898,7 +48690,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -48747,9 +49539,9 @@ var ts; } } // Checks for export * conflicts - var exports = getExportsOfModule(moduleSymbol); - if (exports) { - exports.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -48855,27 +49647,28 @@ var ts; return checkInferType(node); case 178 /* ImportType */: return checkImportType(node); - case 286 /* JSDocAugmentsTag */: + case 289 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 292 /* JSDocTypedefTag */: - return checkJSDocTypedefTag(node); - case 288 /* JSDocParameterTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 292 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: checkSignatureDeclaration(node); // falls through - case 279 /* JSDocNonNullableType */: - case 278 /* JSDocNullableType */: - case 276 /* JSDocAllType */: - case 277 /* JSDocUnknownType */: - case 284 /* JSDocTypeLiteral */: + case 281 /* JSDocNonNullableType */: + case 280 /* JSDocNullableType */: + case 278 /* JSDocAllType */: + case 279 /* JSDocUnknownType */: + case 286 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 275 /* JSDocTypeExpression */: + case 277 /* JSDocTypeExpression */: return checkSourceElement(node.type); case 175 /* IndexedAccessType */: return checkIndexedAccessType(node); @@ -48987,8 +49780,8 @@ var ts; var paramTag = parent.parent; if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. - var host_2 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_2) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -48996,7 +49789,7 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_2.parameters); + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -49059,6 +49852,9 @@ var ts; return ts.Debug.assertNever(kind); } } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -49074,25 +49870,19 @@ var ts; ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); deferredNodes = []; - if (produceDiagnostics) { - ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName)); - allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []); - } ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { if (unusedIsError(kind)) { diagnostics.add(diag); } }); } deferredNodes = undefined; - seenPotentiallyUnusedIdentifiers.clear(); - potentiallyUnusedIdentifiers = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -49388,10 +50178,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 288 /* JSDocParameterTag */) { + if (entityName.parent.kind === 292 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 291 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 295 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -49931,6 +50721,7 @@ var ts; function isRequiredInitializedParameter(parameter) { return strictNullChecks && !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && parameter.initializer && !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } @@ -50181,7 +50972,22 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, - getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); + var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 156 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 155 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 267 /* HeritageClause */; @@ -50217,8 +51023,8 @@ var ts; var decl = _a[_i]; // check meaning of the local symbol to see if declaration needs to be analyzed further if (decl.symbol && decl.symbol.flags & meaning) { - var file = ts.getSourceFileOfNode(decl); - var typeReferenceDirective = fileToDirective.get(file.path); + var file_5 = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file_5.path); if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } @@ -50253,8 +51059,8 @@ var ts; // check that at least one declaration of top level symbol originates from type declaration file for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var file = ts.getSourceFileOfNode(decl); - if (fileToDirective.has(file.path)) { + var file_6 = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file_6.path)) { return true; } } @@ -50272,25 +51078,25 @@ var ts; function initializeTypeChecker() { // Bind all source files and propagate errors for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - ts.bindSourceFile(file, compilerOptions); + var file_7 = _a[_i]; + ts.bindSourceFile(file_7, compilerOptions); } // Initialize global symbol table var augmentations; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { - var file = _c[_b]; - if (!ts.isExternalOrCommonJsModule(file)) { - mergeSymbolTable(globals, file.locals); + var file_8 = _c[_b]; + if (!ts.isExternalOrCommonJsModule(file_8)) { + mergeSymbolTable(globals, file_8.locals); } - if (file.patternAmbientModules && file.patternAmbientModules.length) { - patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + if (file_8.patternAmbientModules && file_8.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file_8.patternAmbientModules); } - if (file.moduleAugmentations.length) { - (augmentations || (augmentations = [])).push(file.moduleAugmentations); + if (file_8.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file_8.moduleAugmentations); } - if (file.symbol && file.symbol.globalExports) { + if (file_8.symbol && file_8.symbol.globalExports) { // Merge in UMD exports with first-in-wins semantics (see #9771) - var source = file.symbol.globalExports; + var source = file_8.symbol.globalExports; source.forEach(function (sourceSymbol, id) { if (!globals.has(id)) { globals.set(id, sourceSymbol); @@ -50742,7 +51548,7 @@ var ts; } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(ts.getEffectiveTypeParameterDeclarations(node), file); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { if (!ts.isArrowFunction(node)) { @@ -51427,8 +52233,8 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + if (ts.isNodeArray(typeParameters)) { + var pos = typeParameters.pos, end = typeParameters.end; return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } @@ -51578,7 +52384,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -51657,10 +52463,8 @@ var ts; if (!elements || elements === ts.emptyArray) { elements = []; } - else { - if (ts.isNodeArray(elements)) { - return elements; - } + else if (ts.isNodeArray(elements)) { + return elements; } var array = elements; array.pos = -1; @@ -51720,6 +52524,13 @@ var ts; node.text = text; return node; } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; function createLiteralFromNode(sourceNode) { var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; @@ -51753,7 +52564,7 @@ var ts; recordTempVariable(name); } if (reservedInNestedScopes) { - name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; } return name; } @@ -51779,7 +52590,7 @@ var ts; /** Create a unique name based on the supplied text. */ function createOptimisticUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateFlags = 3 /* Unique */ | 32 /* Optimistic */; + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -51788,18 +52599,15 @@ var ts; /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ function createFileLevelUniqueName(text) { var name = createOptimisticUniqueName(text); - name.autoGenerateFlags |= 64 /* FileLevel */; + name.autoGenerateFlags |= 32 /* FileLevel */; return name; } ts.createFileLevelUniqueName = createFileLevelUniqueName; - function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { - var name = createIdentifier(""); - name.autoGenerateFlags = 4 /* Node */; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; name.autoGenerateId = nextAutoGenerateId; name.original = node; - if (shouldSkipNameGenerationScope) { - name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; - } nextAutoGenerateId++; return name; } @@ -51890,7 +52698,7 @@ var ts; ts.updateQualifiedName = updateQualifiedName; function parenthesizeForComputedName(expression) { return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) || - expression.kind === 297 /* CommaListExpression */ ? + expression.kind === 301 /* CommaListExpression */ ? createParen(expression) : expression; } @@ -52940,6 +53748,13 @@ var ts; return block; } ts.createBlock = createBlock; + /* @internal */ + function createExpressionStatement(expression) { + var node = createSynthesizedNode(215 /* ExpressionStatement */); + node.expression = expression; + return node; + } + ts.createExpressionStatement = createExpressionStatement; function updateBlock(node, statements) { return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) @@ -52966,9 +53781,7 @@ var ts; } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(215 /* ExpressionStatement */); - node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); - return node; + return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression)); } ts.createStatement = createStatement; function updateStatement(node, expression) { @@ -53864,7 +54677,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295 /* NotEmittedStatement */); + var node = createSynthesizedNode(299 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -53876,7 +54689,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(303 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -53888,7 +54701,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(302 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -53903,7 +54716,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(300 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -53919,7 +54732,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297 /* CommaListExpression */) { + if (node.kind === 301 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -53929,7 +54742,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297 /* CommaListExpression */); + var node = createSynthesizedNode(301 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -53940,15 +54753,31 @@ var ts; : node; } ts.updateCommaList = updateCommaList; - function createBundle(sourceFiles) { + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } var node = ts.createNode(274 /* Bundle */); + node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; - function updateBundle(node, sourceFiles) { - if (node.sourceFiles !== sourceFiles) { - return createBundle(sourceFiles); + function createUnparsedSourceFile(text) { + var node = ts.createNode(275 /* UnparsedSource */); + node.text = text; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration) { + var node = ts.createNode(276 /* InputFiles */); + node.javascriptText = javascript; + node.declarationText = declaration; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); } return node; } @@ -54220,6 +55049,15 @@ var ts; return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); } ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; /** * Gets the constant value to emit for an expression. */ @@ -55192,7 +56030,7 @@ var ts; // if should be wrapped in parens since comma operator has the lowest precedence var emittedExpression = ts.skipPartiallyEmittedExpressions(e); return emittedExpression.kind === 199 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || - emittedExpression.kind === 297 /* CommaListExpression */ + emittedExpression.kind === 301 /* CommaListExpression */ ? ts.createParen(e) : e; } @@ -55212,7 +56050,7 @@ var ts; var check = ts.skipPartiallyEmittedExpressions(e); return (check.kind === 204 /* ClassExpression */ || check.kind === 191 /* FunctionExpression */ || - check.kind === 297 /* CommaListExpression */ || + check.kind === 301 /* CommaListExpression */ || ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */) ? ts.createParen(e) : e; @@ -55333,6 +56171,7 @@ var ts; switch (member.kind) { case 164 /* TypeQuery */: case 174 /* TypeOperator */: + case 171 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -55376,7 +56215,7 @@ var ts; case 184 /* PropertyAccessExpression */: node = node.expression; continue; - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -55406,7 +56245,7 @@ var ts; case 207 /* AsExpression */: case 208 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -55443,7 +56282,7 @@ var ts; case 189 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 207 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 208 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 300 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -55931,7 +56770,7 @@ var ts; statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements); } var declarations = context.endLexicalEnvironment(); - return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); } ts.visitLexicalEnvironment = visitLexicalEnvironment; /** @@ -56228,9 +57067,9 @@ var ts; case 273 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -56286,7 +57125,7 @@ var ts; case 214 /* EmptyStatement */: case 205 /* OmittedExpression */: case 230 /* DebuggerStatement */: - case 295 /* NotEmittedStatement */: + case 299 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -56665,10 +57504,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -56682,8 +57521,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements) - : ts.addRange(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + : ts.prependRange(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -56833,16 +57672,6 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; - function getNamedImportCount(node) { - if (!(node.importClause && node.importClause.namedBindings)) - return 0; - var names = node.importClause.namedBindings; - if (!names) - return 0; - if (!ts.isNamedImports(names)) - return 0; - return names.elements.length; - } function containsDefaultReference(node) { if (!node) return false; @@ -56853,12 +57682,40 @@ var ts; function isNamedDefaultReference(e) { return e.propertyName && e.propertyName.escapedText === "default" /* Default */; } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 273 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; function getImportNeedsImportStarHelper(node) { - return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); } ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { - return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -57595,7 +58452,21 @@ var ts; * at the next execution site, in document order */ var pendingExpressions; - return transformSourceFile; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 274 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText); + } + return prepend; + })); + } /** * Transform TypeScript-specific syntax in a SourceFile. * @@ -58085,7 +58956,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, context.endLexicalEnvironment()); + ts.prependRange(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -58290,7 +59161,7 @@ var ts; // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); var alias = ts.getSynthesizedClone(temp); - alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent @@ -58567,7 +59438,7 @@ var ts; function transformInitializedProperty(property, receiver) { // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) - ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */))) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); @@ -59597,6 +60468,11 @@ var ts; // we can safely elide the parentheses here, as a new synthetic // ParenthesizedExpression will be inserted if we remove parentheses too // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } return ts.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -59702,8 +60578,9 @@ var ts; currentNamespaceContainerName = localName; var statements = []; startLexicalEnvironment(); - ts.addRange(statements, ts.map(node.members, transformEnumMember)); - ts.addRange(statements, endLexicalEnvironment()); + var members = ts.map(node.members, transformEnumMember); + ts.prependRange(statements, endLexicalEnvironment()); + ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); @@ -59943,7 +60820,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -60480,7 +61357,7 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -60752,7 +61629,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -60774,7 +61651,7 @@ var ts; var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); } else { result = expression; @@ -60964,7 +61841,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -61042,9 +61919,14 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -61346,7 +62228,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -61371,11 +62253,11 @@ var ts; statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); } ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); - var trailingStatements = endLexicalEnvironment(); - if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) { + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.prependRange(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); - ts.addRange(statements, trailingStatements); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } return body; @@ -61533,7 +62415,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -61550,7 +62432,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -61561,7 +62443,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -61575,7 +62457,7 @@ var ts; function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transform JSX-specific syntax in a SourceFile. * @@ -62083,7 +62965,7 @@ var ts; (function (ts) { function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -62291,7 +63173,7 @@ var ts; * be reset. */ var enabledSubstitutions; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -62467,7 +63349,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -62721,7 +63603,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -62834,7 +63716,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -63469,6 +64351,7 @@ var ts; var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression); ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); statements.push(returnStatement); // To align with the source map emit for the old emitter, we set a custom @@ -63476,7 +64359,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); + ts.prependRange(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { @@ -64057,7 +64940,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.addRange(statements_4, lexicalEnvironment); + ts.prependRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -64510,10 +65393,12 @@ var ts; // We skip any outer expressions in a number of places to get to the innermost // expression, but we will restore them later to preserve comments and source maps. var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); - // The class statements are the statements generated by visiting the first statement of the + // The class statements are the statements generated by visiting the first statement with initializer of the // body (1), while all other statements are added to remainingStatements (2) - var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); - var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); // We know there is only one variable declaration here as we verified this in an // earlier call to isTypeScriptClassWrapper @@ -64523,6 +65408,7 @@ var ts; // we see as an assignment, for example: // // (function () { + // var C_1; // var C = C_1 = (function () { // function C() { // } @@ -64531,7 +65417,6 @@ var ts; // }()); // C = C_1 = __decorate([dec], C); // return C; - // var C_1; // }()) // var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); @@ -65161,7 +66046,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.enableSubstitution(184 /* PropertyAccessExpression */); context.enableSubstitution(269 /* PropertyAssignment */); - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. * @@ -65473,7 +66358,7 @@ var ts; var exceptionBlockStack; // A stack of containing exception blocks. var currentExceptionBlock; // The current exception block. var withBlockStack; // A stack containing `with` blocks. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; @@ -65730,7 +66615,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -67923,7 +68808,7 @@ var ts; var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -67966,7 +68851,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -68189,7 +69074,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -68211,7 +69096,7 @@ var ts; */ function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); if (expressionResult) { if (emitAsReturn) { var statement = ts.createReturn(expressionResult); @@ -68252,29 +69137,84 @@ var ts; return visitFunctionDeclaration(node); case 234 /* ClassDeclaration */: return visitClassDeclaration(node); - case 298 /* MergeDeclarationMarker */: + case 302 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 303 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } - function importCallExpressionVisitor(node) { - // This visitor does not need to descend into the tree if there is no dynamic import, + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } else { - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 269 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 270 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 271 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 153 /* MethodDeclaration */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } function visitImportCallExpression(node) { - var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: @@ -68568,10 +69508,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -68585,13 +69525,13 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), - /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), /*location*/ node), /*original*/ node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -68613,10 +69553,10 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -68661,7 +69601,7 @@ var ts; } } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -68673,6 +69613,21 @@ var ts; } return ts.singleOrMany(statements); } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } /** * Transforms an exported variable with an initializer into an expression. * @@ -68680,13 +69635,13 @@ var ts; */ function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), /*visitor*/ undefined, context, 0 /* All */, - /*needsValue*/ false, createExportExpression); + /*needsValue*/ false, createAllExportExpressions); } else { return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), - /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); } } /** @@ -69090,8 +70045,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { - var exportName = exportedNames_1[_i]; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression, /*location*/ node); @@ -69127,8 +70082,8 @@ var ts; ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; - for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { - var exportName = exportedNames_2[_i]; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); @@ -69215,7 +70170,7 @@ var ts; var hoistedStatements; var enclosingBlockScopedContainer; var noSubstitution; // Set of nodes for which substitution rules should be ignored. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -69388,7 +70343,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -69518,12 +70473,12 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_2 = dependencyGroups_1[_i]; + var group_1 = dependencyGroups_1[_i]; // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -70116,9 +71071,9 @@ var ts; return visitCatchClause(node); case 212 /* Block */: return visitBlock(node); - case 298 /* MergeDeclarationMarker */: + case 302 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 303 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -70551,8 +71506,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { - var exportName = exportedNames_3[_i]; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } return expression; @@ -70585,8 +71540,8 @@ var ts; var expression = node.kind === 198 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; - for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { - var exportName = exportedNames_4[_i]; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } if (node.kind === 198 /* PostfixUnaryExpression */) { @@ -70653,7 +71608,7 @@ var ts; context.enableEmitNotification(273 /* SourceFile */); context.enableSubstitution(71 /* Identifier */); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -71160,7 +72115,12 @@ var ts; return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */; /** * Transforms a ts file into a .d.ts file * This process requires type information, which is retrieved through the emit resolver. Because of this, @@ -71180,19 +72140,22 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, - reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, }; var errorNameNode; var currentSourceFile; + var refs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); var noResolve = options.noResolve, stripInternal = options.stripInternal; - var host = context.getEmitHost(); return transformRoot; function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { if (!typeReferenceDirectives) { @@ -71204,6 +72167,10 @@ var ts; necessaryTypeRefernces.set(ref, true); } } + function trackReferencedAmbientModule(node) { + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } function handleSymbolAccessibilityError(symbolAccessibilityResult) { if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info @@ -71234,6 +72201,8 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } @@ -71277,12 +72246,16 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - return ts.updateSourceFileNode(sourceFile, filterCandidateImports(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText); + } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); @@ -71305,13 +72278,13 @@ var ts; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); necessaryTypeRefernces = undefined; - var refs = collectReferences(currentSourceFile, ts.createMap()); + refs = collectReferences(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); - refs.forEach(referenceVisitor); var statements = ts.visitNodes(node.statements, visitDeclarationStatements); - var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); @@ -71323,17 +72296,19 @@ var ts; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports - for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { - var importStatement = emittedImports_1[_i]; - if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { - var expr = importStatement.moduleReference.expression; - if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { return undefined; } } - else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { - return undefined; - } } return { fileName: typeName, pos: -1, end: -1 }; } @@ -71366,7 +72341,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); if (elem) { - ret.set("" + ts.getNodeId(elem), elem); + ret.set("" + ts.getOriginalNodeId(elem), elem); } }); return ret; @@ -71583,7 +72558,7 @@ var ts; } // Nothing visible } - function filterCandidateImports(statements) { + function transformAndReplaceLatePaintedStatements(statements) { // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during // error handling which must now be included in the output and themselves checked for errors. // For example: @@ -71598,62 +72573,45 @@ var ts; // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. - var unconsideredStatements = []; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); - if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope - unconsideredStatements.push(i); - continue; - } if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was foudn which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); - } - switch (i.kind) { - case 242 /* ImportEqualsDeclaration */: { - var result = transformImportEqualsDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 243 /* ImportDeclaration */: { - var result = transformImportDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 213 /* VariableStatement */: { - var result = transformVariableStatement(i, /*privateDeclaration*/ true); // Transform the statement (potentially again, possibly revealing more sub-nodes) - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - default: ts.Debug.assertNever(i, "Unhandled late painted statement!"); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } - // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not - // be considered in the child scope - lateMarkedStatements = unconsideredStatements; // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list // (and remove them from the set to examine for outter declarations) return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); - } - function visitLateVisibilityMarkedStatements(statement) { - if (ts.isLateVisibilityPaintedStatement(statement)) { - var key = "" + ts.getNodeId(statement); - if (lateStatementReplacementMap.has(key)) { - var result = lateStatementReplacementMap.get(key); - lateStatementReplacementMap.delete(key); - if (result && ts.isSourceFile(statement.parent) && !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */)) { - // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier - needsScopeFixMarker = true; + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; } - return result; } - else { - return ts.getParseTreeNode(statement) ? undefined : statement; - } - } - else { return statement; } } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } function visitDeclarationSubtree(input) { if (shouldStripInternal(input)) return; @@ -71851,13 +72809,21 @@ var ts; return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } - case 242 /* ImportEqualsDeclaration */: + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 242 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } case 243 /* ImportDeclaration */: { - // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later - // to reduce the likelihood we need to rewrite it - lateMarkedStatements = lateMarkedStatements || []; - ts.pushIfUnique(lateMarkedStatements, input); - return input; + return transformImportDeclaration(input); } } if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) @@ -71870,52 +72836,53 @@ var ts; previousEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = input; } - var previousNeedsDeclare; var canProdiceDiagnostic = ts.canProduceDiagnostics(input); var oldDiag = getSymbolAccessibilityDiagnostic; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); } - var oldPossibleImports; + var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 236 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(ts.updateTypeAliasDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 235 /* InterfaceDeclaration */: { return cleanup(ts.updateInterfaceDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 233 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type return cleanup(ts.updateFunctionDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), + /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); } case 238 /* ModuleDeclaration */: { - previousNeedsDeclare = needsDeclare; needsDeclare = false; - oldPossibleImports = lateMarkedStatements; - lateMarkedStatements = undefined; var inner = input.body; if (inner && inner.kind === 239 /* ModuleBlock */) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); - var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); return cleanup(ts.updateModuleDeclaration(input, /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); return cleanup(ts.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + /*decorators*/ undefined, mods, input.name, body)); } } case 234 /* ClassDeclaration */: { - var modifiers = ts.createNodeArray(ensureModifiers(input)); + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); var parameterProperties = void 0; @@ -71985,12 +72952,10 @@ var ts; } } case 213 /* VariableStatement */: { - var result = transformVariableStatement(input); - lateStatementReplacementMap.set("" + ts.getNodeId(input), result); // Don't actually elide yet; just leave as original node - will be elided/swapped by late pass - return cleanup(input); + return cleanup(transformVariableStatement(input, isPrivate)); } case 237 /* EnumDeclaration */: { - return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; // Rewrite enum values to their constants, if available @@ -72001,27 +72966,20 @@ var ts; } // Anything left unhandled is an error, so this should be unreachable return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); - function cleanup(returnValue) { + function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; } - if (input.kind === 238 /* ModuleDeclaration */) { - needsDeclare = previousNeedsDeclare; - lateMarkedStatements = ts.concatenate(oldPossibleImports, lateMarkedStatements); - } if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (returnValue && (!ts.isLateVisibilityPaintedStatement(input) || lateStatementReplacementMap.get("" + ts.getNodeId(input)))) { - if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) { - // Exported top-level member indicates moduleness - resultHasExternalModuleIndicator = true; - } + if (input.kind === 238 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; } - if (returnValue === input) { - return returnValue; + if (node === input) { + return node; } - return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } function transformVariableStatement(input, privateDeclaration) { @@ -72098,7 +73056,7 @@ var ts; return maskModifierFlags(node, mask, additions); } function ensureAccessor(node) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + var accessors = resolver.getAllAccessorDeclarations(node); if (node.kind !== accessors.firstAccessor.kind) { return; } @@ -72111,7 +73069,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -72125,7 +73083,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -72287,7 +73245,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(300 /* Count */); + var enabledSyntaxKindFeatures = new Array(304 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -72782,7 +73740,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 295 /* NotEmittedStatement */ + if (node.kind !== 299 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -72799,7 +73757,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 295 /* NotEmittedStatement */ + if (node.kind !== 299 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -72975,7 +73933,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 299 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -73299,6 +74257,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); /*@internal*/ /** @@ -73315,7 +74274,7 @@ var ts; var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var bundle = ts.createBundle(sourceFiles); + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; @@ -73341,7 +74300,8 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); @@ -73350,17 +74310,27 @@ var ts; var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } if (options.jsx === 1 /* Preserve */) { if (ts.isSourceFileJavaScript(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { @@ -73374,9 +74344,10 @@ var ts; } return ".js" /* Js */; } + ts.getOutputExtension = getOutputExtension; /*@internal*/ // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; @@ -73390,6 +74361,7 @@ var ts; mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, }); + var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; // Emit each output file ts.performance.mark("beforePrint"); @@ -73402,8 +74374,8 @@ var ts; sourceMaps: sourceMapDataList }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -73415,10 +74387,12 @@ var ts; if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } } - function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { - var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { // Make sure not to write js file and source map file if any of them cannot be written if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { emitSkipped = true; @@ -73428,7 +74402,7 @@ var ts; return; } // Transform the source files - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false); + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); // Create a printer to print the nodes var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { // resolver hooks @@ -73443,7 +74417,8 @@ var ts; // emitter hooks onSetSourceFile: setSourceFile, }); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); // Clean up emit nodes on parse tree transform.dispose(); } @@ -73454,8 +74429,8 @@ var ts; var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); - var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; - var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); if (ts.length(declarationTransform.diagnostics)) { for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { var diagnostic = _b[_a]; @@ -73477,17 +74452,18 @@ var ts; var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); } declarationTransform.dispose(); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 274 /* Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 273 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { - printer.writeBundle(bundle, writer); + printer.writeBundle(bundle, writer, bundleInfo); } else { printer.writeFile(sourceFile, writer); @@ -73503,9 +74479,15 @@ var ts; } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } // Reset state mapRecorder.reset(); writer.clear(); + bundleInfo = createDefaultBundleInfo(); } function setSourceFile(node) { sourceMap.setSourceFile(node); @@ -73515,6 +74497,13 @@ var ts; } } ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } @@ -73572,6 +74561,7 @@ var ts; switch (node.kind) { case 273 /* SourceFile */: return printFile(node); case 274 /* Bundle */: return printBundle(node); + case 275 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -73588,6 +74578,10 @@ var ts; writeFile(sourceFile, beginPrint()); return endPrint(); } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; setWriter(output); @@ -73605,7 +74599,7 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output) { + function writeBundle(bundle, output, bundleInfo) { isOwnFileEmit = false; var previousWriter = writer; setWriter(output); @@ -73613,13 +74607,28 @@ var ts; emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); - for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { - var sourceFile = _b[_a]; + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + writeLine(); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; print(0 /* SourceFile */, sourceFile, sourceFile); } reset(); writer = previousWriter; } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } function writeFile(sourceFile, output) { isOwnFileEmit = true; var previousWriter = writer; @@ -73642,7 +74651,8 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmitWithNotification(hint, node); + var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -73665,417 +74675,422 @@ var ts; comments.reset(); setWriter(/*output*/ undefined); } - // TODO: Should this just be `emit`? - // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034 - function emitIfPresent(node) { - if (node) { - emit(node); - } - } function emit(node) { - pipelineEmitWithNotification(4 /* Unspecified */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - pipelineEmitWithNotification(2 /* IdentifierName */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - pipelineEmitWithNotification(1 /* Expression */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, hint) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Comments */: + if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + return pipelineEmitWithComments; + } + return pipelineEmitWithoutComments; + case 2 /* SourceMaps */: + if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { + return pipelineEmitWithSourceMap; + } + // falls through + case 3 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + } + } + function getNextPipelinePhase(currentPhase, hint) { + return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - if (onEmitNode) { - onEmitNode(hint, node, pipelineEmitWithComments); - } - else { - pipelineEmitWithComments(hint, node); - } + ts.Debug.assertDefined(onEmitNode); + onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); } function pipelineEmitWithComments(hint, node) { - node = trySubstituteNode(hint, node); - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { - emitNodeWithComments(hint, node, pipelineEmitWithSourceMap); - } - else { - pipelineEmitWithSourceMap(hint, node); - } + ts.Debug.assertDefined(emitNodeWithComments); + ts.Debug.assert(hint !== 0 /* SourceFile */); + emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); + } + function pipelineEmitWithoutComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); + pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); - } - else { - pipelineEmitWithHint(hint, node); - } + ts.Debug.assertDefined(onEmitSourceMapOfNode); + ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */); + onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { - switch (hint) { - case 0 /* SourceFile */: return pipelineEmitSourceFile(node); - case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node); - case 1 /* Expression */: return pipelineEmitExpression(node); - case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 4 /* Unspecified */: return pipelineEmitUnspecified(node); + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + return emitLiteral(node); + case 275 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 145 /* QualifiedName */: + return emitQualifiedName(node); + case 146 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 147 /* TypeParameter */: + return emitTypeParameter(node); + case 148 /* Parameter */: + return emitParameter(node); + case 149 /* Decorator */: + return emitDecorator(node); + // Type members + case 150 /* PropertySignature */: + return emitPropertySignature(node); + case 151 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 152 /* MethodSignature */: + return emitMethodSignature(node); + case 153 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 154 /* Constructor */: + return emitConstructor(node); + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 157 /* CallSignature */: + return emitCallSignature(node); + case 158 /* ConstructSignature */: + return emitConstructSignature(node); + case 159 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 160 /* TypePredicate */: + return emitTypePredicate(node); + case 161 /* TypeReference */: + return emitTypeReference(node); + case 162 /* FunctionType */: + return emitFunctionType(node); + case 283 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 163 /* ConstructorType */: + return emitConstructorType(node); + case 164 /* TypeQuery */: + return emitTypeQuery(node); + case 165 /* TypeLiteral */: + return emitTypeLiteral(node); + case 166 /* ArrayType */: + return emitArrayType(node); + case 167 /* TupleType */: + return emitTupleType(node); + case 168 /* UnionType */: + return emitUnionType(node); + case 169 /* IntersectionType */: + return emitIntersectionType(node); + case 170 /* ConditionalType */: + return emitConditionalType(node); + case 171 /* InferType */: + return emitInferType(node); + case 172 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 206 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 173 /* ThisType */: + return emitThisType(); + case 174 /* TypeOperator */: + return emitTypeOperator(node); + case 175 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 176 /* MappedType */: + return emitMappedType(node); + case 177 /* LiteralType */: + return emitLiteralType(node); + case 178 /* ImportType */: + return emitImportTypeNode(node); + case 278 /* JSDocAllType */: + write("*"); + return; + case 279 /* JSDocUnknownType */: + write("?"); + return; + case 280 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 281 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 282 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 284 /* JSDocVariadicType */: + return emitJSDocVariadicType(node); + // Binding patterns + case 179 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 180 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 181 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 210 /* TemplateSpan */: + return emitTemplateSpan(node); + case 211 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 212 /* Block */: + return emitBlock(node); + case 213 /* VariableStatement */: + return emitVariableStatement(node); + case 214 /* EmptyStatement */: + return emitEmptyStatement(); + case 215 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 216 /* IfStatement */: + return emitIfStatement(node); + case 217 /* DoStatement */: + return emitDoStatement(node); + case 218 /* WhileStatement */: + return emitWhileStatement(node); + case 219 /* ForStatement */: + return emitForStatement(node); + case 220 /* ForInStatement */: + return emitForInStatement(node); + case 221 /* ForOfStatement */: + return emitForOfStatement(node); + case 222 /* ContinueStatement */: + return emitContinueStatement(node); + case 223 /* BreakStatement */: + return emitBreakStatement(node); + case 224 /* ReturnStatement */: + return emitReturnStatement(node); + case 225 /* WithStatement */: + return emitWithStatement(node); + case 226 /* SwitchStatement */: + return emitSwitchStatement(node); + case 227 /* LabeledStatement */: + return emitLabeledStatement(node); + case 228 /* ThrowStatement */: + return emitThrowStatement(node); + case 229 /* TryStatement */: + return emitTryStatement(node); + case 230 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 231 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 232 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 233 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 234 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 235 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 236 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 237 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 238 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 239 /* ModuleBlock */: + return emitModuleBlock(node); + case 240 /* CaseBlock */: + return emitCaseBlock(node); + case 241 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 242 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 243 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 244 /* ImportClause */: + return emitImportClause(node); + case 245 /* NamespaceImport */: + return emitNamespaceImport(node); + case 246 /* NamedImports */: + return emitNamedImports(node); + case 247 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 248 /* ExportAssignment */: + return emitExportAssignment(node); + case 249 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 250 /* NamedExports */: + return emitNamedExports(node); + case 251 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 252 /* MissingDeclaration */: + return; + // Module references + case 253 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 10 /* JsxText */: + return emitJsxText(node); + case 256 /* JsxOpeningElement */: + case 259 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 257 /* JsxClosingElement */: + case 260 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 261 /* JsxAttribute */: + return emitJsxAttribute(node); + case 262 /* JsxAttributes */: + return emitJsxAttributes(node); + case 263 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 264 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 265 /* CaseClause */: + return emitCaseClause(node); + case 266 /* DefaultClause */: + return emitDefaultClause(node); + case 267 /* HeritageClause */: + return emitHeritageClause(node); + case 268 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 269 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 270 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 271 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 272 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (ignored) + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + node = trySubstituteNode(1 /* Expression */, node); + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + return emitNumericLiteral(node); + case 9 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 97 /* SuperKeyword */: + case 101 /* TrueKeyword */: + case 99 /* ThisKeyword */: + case 91 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 182 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 183 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 184 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 185 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 186 /* CallExpression */: + return emitCallExpression(node); + case 187 /* NewExpression */: + return emitNewExpression(node); + case 188 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 189 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 190 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 191 /* FunctionExpression */: + return emitFunctionExpression(node); + case 192 /* ArrowFunction */: + return emitArrowFunction(node); + case 193 /* DeleteExpression */: + return emitDeleteExpression(node); + case 194 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 195 /* VoidExpression */: + return emitVoidExpression(node); + case 196 /* AwaitExpression */: + return emitAwaitExpression(node); + case 197 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 198 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 199 /* BinaryExpression */: + return emitBinaryExpression(node); + case 200 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 201 /* TemplateExpression */: + return emitTemplateExpression(node); + case 202 /* YieldExpression */: + return emitYieldExpression(node); + case 203 /* SpreadElement */: + return emitSpreadExpression(node); + case 204 /* ClassExpression */: + return emitClassExpression(node); + case 205 /* OmittedExpression */: + return; + case 207 /* AsExpression */: + return emitAsExpression(node); + case 208 /* NonNullExpression */: + return emitNonNullExpression(node); + case 209 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 254 /* JsxElement */: + return emitJsxElement(node); + case 255 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 258 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 300 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 301 /* CommaListExpression */: + return emitCommaList(node); + } } - } - function pipelineEmitSourceFile(node) { - ts.Debug.assertNode(node, ts.isSourceFile); - emitSourceFile(node); - } - function pipelineEmitIdentifierName(node) { - ts.Debug.assertNode(node, ts.isIdentifier); - emitIdentifier(node); } function emitMappedTypeParameter(node) { emit(node.name); writeSpace(); writeKeyword("in"); writeSpace(); - emitIfPresent(node.constraint); - } - function pipelineEmitUnspecified(node) { - var kind = node.kind; - // Reserved words - // Strict mode reserved words - // Contextual keywords - if (ts.isKeyword(kind)) { - writeTokenNode(node, writeKeyword); - return; - } - switch (kind) { - // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Parse tree nodes - // Names - case 145 /* QualifiedName */: - return emitQualifiedName(node); - case 146 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 147 /* TypeParameter */: - return emitTypeParameter(node); - case 148 /* Parameter */: - return emitParameter(node); - case 149 /* Decorator */: - return emitDecorator(node); - // Type members - case 150 /* PropertySignature */: - return emitPropertySignature(node); - case 151 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 152 /* MethodSignature */: - return emitMethodSignature(node); - case 153 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 154 /* Constructor */: - return emitConstructor(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 157 /* CallSignature */: - return emitCallSignature(node); - case 158 /* ConstructSignature */: - return emitConstructSignature(node); - case 159 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 160 /* TypePredicate */: - return emitTypePredicate(node); - case 161 /* TypeReference */: - return emitTypeReference(node); - case 162 /* FunctionType */: - return emitFunctionType(node); - case 281 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 163 /* ConstructorType */: - return emitConstructorType(node); - case 164 /* TypeQuery */: - return emitTypeQuery(node); - case 165 /* TypeLiteral */: - return emitTypeLiteral(node); - case 166 /* ArrayType */: - return emitArrayType(node); - case 167 /* TupleType */: - return emitTupleType(node); - case 168 /* UnionType */: - return emitUnionType(node); - case 169 /* IntersectionType */: - return emitIntersectionType(node); - case 170 /* ConditionalType */: - return emitConditionalType(node); - case 171 /* InferType */: - return emitInferType(node); - case 172 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 206 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 173 /* ThisType */: - return emitThisType(); - case 174 /* TypeOperator */: - return emitTypeOperator(node); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 176 /* MappedType */: - return emitMappedType(node); - case 177 /* LiteralType */: - return emitLiteralType(node); - case 178 /* ImportType */: - return emitImportTypeNode(node); - case 276 /* JSDocAllType */: - write("*"); - return; - case 277 /* JSDocUnknownType */: - write("?"); - return; - case 278 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 279 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 280 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 282 /* JSDocVariadicType */: - return emitJSDocVariadicType(node); - // Binding patterns - case 179 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 180 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 181 /* BindingElement */: - return emitBindingElement(node); - // Misc - case 210 /* TemplateSpan */: - return emitTemplateSpan(node); - case 211 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Statements - case 212 /* Block */: - return emitBlock(node); - case 213 /* VariableStatement */: - return emitVariableStatement(node); - case 214 /* EmptyStatement */: - return emitEmptyStatement(); - case 215 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 216 /* IfStatement */: - return emitIfStatement(node); - case 217 /* DoStatement */: - return emitDoStatement(node); - case 218 /* WhileStatement */: - return emitWhileStatement(node); - case 219 /* ForStatement */: - return emitForStatement(node); - case 220 /* ForInStatement */: - return emitForInStatement(node); - case 221 /* ForOfStatement */: - return emitForOfStatement(node); - case 222 /* ContinueStatement */: - return emitContinueStatement(node); - case 223 /* BreakStatement */: - return emitBreakStatement(node); - case 224 /* ReturnStatement */: - return emitReturnStatement(node); - case 225 /* WithStatement */: - return emitWithStatement(node); - case 226 /* SwitchStatement */: - return emitSwitchStatement(node); - case 227 /* LabeledStatement */: - return emitLabeledStatement(node); - case 228 /* ThrowStatement */: - return emitThrowStatement(node); - case 229 /* TryStatement */: - return emitTryStatement(node); - case 230 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 231 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 232 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 233 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 234 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 235 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 236 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 237 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 238 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 239 /* ModuleBlock */: - return emitModuleBlock(node); - case 240 /* CaseBlock */: - return emitCaseBlock(node); - case 241 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 242 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 243 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 244 /* ImportClause */: - return emitImportClause(node); - case 245 /* NamespaceImport */: - return emitNamespaceImport(node); - case 246 /* NamedImports */: - return emitNamedImports(node); - case 247 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 248 /* ExportAssignment */: - return emitExportAssignment(node); - case 249 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 250 /* NamedExports */: - return emitNamedExports(node); - case 251 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 252 /* MissingDeclaration */: - return; - // Module references - case 253 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX (non-expression) - case 10 /* JsxText */: - return emitJsxText(node); - case 256 /* JsxOpeningElement */: - case 259 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 257 /* JsxClosingElement */: - case 260 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 261 /* JsxAttribute */: - return emitJsxAttribute(node); - case 262 /* JsxAttributes */: - return emitJsxAttributes(node); - case 263 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 264 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 265 /* CaseClause */: - return emitCaseClause(node); - case 266 /* DefaultClause */: - return emitDefaultClause(node); - case 267 /* HeritageClause */: - return emitHeritageClause(node); - case 268 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 269 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 270 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 271 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 272 /* EnumMember */: - return emitEnumMember(node); - // JSDoc nodes (ignored) - // Transformation nodes (ignored) - } - // If the node is an expression, try to emit it as an expression with - // substitution. - if (ts.isExpression(node)) { - return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); - } - if (ts.isToken(node)) { - writeTokenNode(node, writePunctuation); - return; - } - } - function pipelineEmitExpression(node) { - var kind = node.kind; - switch (kind) { - // Literals - case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; - // Expressions - case 182 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 183 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 184 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 185 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 186 /* CallExpression */: - return emitCallExpression(node); - case 187 /* NewExpression */: - return emitNewExpression(node); - case 188 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 189 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 190 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 191 /* FunctionExpression */: - return emitFunctionExpression(node); - case 192 /* ArrowFunction */: - return emitArrowFunction(node); - case 193 /* DeleteExpression */: - return emitDeleteExpression(node); - case 194 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 195 /* VoidExpression */: - return emitVoidExpression(node); - case 196 /* AwaitExpression */: - return emitAwaitExpression(node); - case 197 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 198 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 199 /* BinaryExpression */: - return emitBinaryExpression(node); - case 200 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 201 /* TemplateExpression */: - return emitTemplateExpression(node); - case 202 /* YieldExpression */: - return emitYieldExpression(node); - case 203 /* SpreadElement */: - return emitSpreadExpression(node); - case 204 /* ClassExpression */: - return emitClassExpression(node); - case 205 /* OmittedExpression */: - return; - case 207 /* AsExpression */: - return emitAsExpression(node); - case 208 /* NonNullExpression */: - return emitNonNullExpression(node); - case 209 /* MetaProperty */: - return emitMetaProperty(node); - // JSX - case 254 /* JsxElement */: - return emitJsxElement(node); - case 255 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 258 /* JsxFragment */: - return emitJsxFragment(node); - // Transformation nodes - case 296 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 297 /* CommaListExpression */: - return emitCommaList(node); - } + emit(node.constraint); } function trySubstituteNode(hint, node) { return node && substituteNode && substituteNode(hint, node) || node; @@ -74151,6 +75166,10 @@ var ts; writeStringLiteral(text); } } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + write(unparsed.text); + } // // Identifiers // @@ -74201,13 +75220,11 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.dotDotDotToken); - if (node.name) { - emitNodeWithWriter(node.name, writeParameter); - } - emitIfPresent(node.questionToken); - if (node.parent && node.parent.kind === 281 /* JSDocFunctionType */ && !node.name) { - emitIfPresent(node.type); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 283 /* JSDocFunctionType */ && !node.name) { + emit(node.type); } else { emitTypeAnnotation(node.type); @@ -74226,7 +75243,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeAnnotation(node.type); writeSemicolon(); } @@ -74234,28 +75251,30 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); - emitIfPresent(node.exclamationToken); + emit(node.questionToken); + emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -74272,14 +75291,17 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitCallSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitConstructSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("new"); @@ -74288,6 +75310,7 @@ var ts; emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); @@ -74314,18 +75337,20 @@ var ts; emitTypeArguments(node, node.typeArguments); } function emitFunctionType(node) { + pushNameGenerationScope(node); emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitJSDocFunctionType(node) { write("function"); emitParameters(node, node.parameters); write(":"); - emitIfPresent(node.type); + emit(node.type); } function emitJSDocNullableType(node) { write("?"); @@ -74340,6 +75365,7 @@ var ts; write("="); } function emitConstructorType(node) { + pushNameGenerationScope(node); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -74347,7 +75373,8 @@ var ts; writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitTypeQuery(node) { writeKeyword("typeof"); @@ -74437,7 +75464,8 @@ var ts; writeSpace(); } writePunctuation("["); - pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); @@ -74447,7 +75475,7 @@ var ts; } writePunctuation(":"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); writeSemicolon(); if (emitFlags & 1 /* SingleLine */) { writeSpace(); @@ -74490,7 +75518,7 @@ var ts; writePunctuation("]"); } function emitBindingElement(node) { - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); if (node.propertyName) { emit(node.propertyName); writePunctuation(":"); @@ -74508,6 +75536,7 @@ var ts; emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); @@ -74597,6 +75626,7 @@ var ts; emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { @@ -74696,7 +75726,7 @@ var ts; } function emitYieldExpression(node) { emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { @@ -74704,6 +75734,7 @@ var ts; emitExpression(node.expression); } function emitClassExpression(node) { + generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { @@ -74757,7 +75788,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - writeSemicolon(); + if (!ts.isJsonSourceFile(currentSourceFile)) { + writeSemicolon(); + } } function emitIfStatement(node) { var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); @@ -74953,7 +75986,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -74970,6 +76003,8 @@ var ts; increaseIndent(); } pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); emitSignatureHead(node); if (onEmitNode) { onEmitNode(4 /* Unspecified */, body, emitBlockCallback); @@ -75065,6 +76100,7 @@ var ts; emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("class"); @@ -75142,6 +76178,7 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); popNameGenerationScope(node); } @@ -75183,12 +76220,12 @@ var ts; writeSemicolon(); } function emitImportClause(node) { - emitIfPresent(node.name); + emit(node.name); if (node.name && node.namedBindings) { emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } - emitIfPresent(node.namedBindings); + emit(node.namedBindings); } function emitNamespaceImport(node) { var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); @@ -75330,7 +76367,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { writePunctuation("{"); - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); emitExpression(node.expression); writePunctuation("}"); } @@ -75486,8 +76523,8 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { - var directive = types_18[_d]; + for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { + var directive = types_17[_d]; write("/// "); writeLine(); } @@ -75495,6 +76532,7 @@ var ts; function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); @@ -75571,6 +76609,8 @@ var ts; // Helpers // function emitNodeWithWriter(node, writer) { + if (!node) + return; var savedWrite = write; write = writer; emit(node); @@ -76060,7 +77100,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return generateName(node); } - else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { @@ -76112,6 +77152,113 @@ var ts; } reservedNames.set(name, true); } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 212 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 227 /* LabeledStatement */: + case 225 /* WithStatement */: + case 217 /* DoStatement */: + case 218 /* WhileStatement */: + generateNames(node.statement); + break; + case 216 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 219 /* ForStatement */: + case 221 /* ForOfStatement */: + case 220 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 226 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 240 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 265 /* CaseClause */: + case 266 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 229 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 268 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 213 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 232 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 231 /* VariableDeclaration */: + case 148 /* Parameter */: + case 181 /* BindingElement */: + case 234 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 233 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 179 /* ObjectBindingPattern */: + case 180 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 243 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 244 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 245 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 246 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 247 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 269 /* PropertyAssignment */: + case 270 /* ShorthandPropertyAssignment */: + case 151 /* PropertyDeclaration */: + case 153 /* MethodDeclaration */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } /** * Generate the text for a generated identifier. */ @@ -76119,17 +77266,7 @@ var ts; if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { - var savedTempFlags = tempFlags; - popNameGenerationScope(/*node*/ undefined); - var result = generateNameCached(getNodeForGeneratedName(name)); - pushNameGenerationScope(/*node*/ undefined); - tempFlags = savedTempFlags; - return result; - } - else { - return generateNameCached(getNodeForGeneratedName(name)); - } + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); } else { // Auto, Loop, and Unique names are cached based on their unique @@ -76138,9 +77275,9 @@ var ts; return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } - function generateNameCached(node) { + function generateNameCached(node, flags) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); } /** * Returns a value indicating whether a name is unique globally, within the current file, @@ -76155,7 +77292,7 @@ var ts; * Returns a value indicating whether a name is unique globally or within the current file. */ function isFileLevelUniqueName(name) { - return ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName); + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; } /** * Returns a value indicating whether a name is unique within a container. @@ -76212,11 +77349,16 @@ var ts; * makeUniqueName are guaranteed to never conflict. * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName, checkFn, optimistic) { + function makeUniqueName(baseName, checkFn, optimistic, scoped) { if (checkFn === void 0) { checkFn = isUniqueName; } if (optimistic) { if (checkFn(baseName)) { - generatedNames.set(baseName, true); + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } return baseName; } } @@ -76228,7 +77370,12 @@ var ts; while (true) { var generatedName = baseName + i; if (checkFn(generatedName)) { - generatedNames.set(generatedName, true); + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } return generatedName; } i++; @@ -76275,10 +77422,10 @@ var ts; /** * Generates a unique name from a node. */ - function generateNameForNode(node) { + function generateNameForNode(node, flags) { switch (node.kind) { case 71 /* Identifier */: - return makeUniqueName(getTextOfNode(node)); + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); case 238 /* ModuleDeclaration */: case 237 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); @@ -76305,11 +77452,11 @@ var ts; function makeName(name) { switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 3 /* Unique */: - return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 64 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 32 /* Optimistic */)); + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -76325,7 +77472,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateFlags === 4 /* Node */ + && !!(node.autoGenerateFlags & 4 /* Node */) && node.autoGenerateId !== autoGenerateId) { break; } @@ -76384,7 +77531,7 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); } function getCachedFileSystemEntriesForBaseDir(path) { return getCachedFileSystemEntries(ts.getDirectoryPath(path)); @@ -76397,7 +77544,7 @@ var ts; files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], directories: host.getDirectories(rootDir) || [] }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); return resultFromHost; } /** @@ -76406,6 +77553,7 @@ var ts; * The host request is done under try catch block to avoid caching incorrect result */ function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); var cachedResult = getCachedFileSystemEntries(rootDirPath); if (cachedResult) { return cachedResult; @@ -76415,7 +77563,7 @@ var ts; } catch (_e) { // If there is exception to read directories, dont cache the result and direct the calls to host - ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); return undefined; } } @@ -76451,7 +77599,7 @@ var ts; } function directoryExists(dirPath) { var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); } function createDirectory(dirPath) { var path = toPath(dirPath); @@ -76725,7 +77873,7 @@ var ts; if (!commonPathComponents) { // Can happen when all input files are .d.ts files return currentDirectory; } - return ts.getNormalizedPathFromPathComponents(commonPathComponents); + return ts.getPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { @@ -76832,7 +77980,8 @@ var ts; directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, - realpath: realpath + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); } }; } ts.createCompilerHost = createCompilerHost; @@ -76900,52 +78049,52 @@ var ts; var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; - var context = ""; + var context_2 = ""; if (diagnostic.file) { - var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; - var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var start = diagnostic.start, length_4 = diagnostic.length, file_9 = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file_9, start + length_4), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file_9, file_9.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file_9.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_9.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; var gutterWidth = (lastLine + 1 + "").length; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } for (var i = firstLine; i <= lastLine; i++) { - context += host.getNewLine(); + context_2 += host.getNewLine(); // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context_2 += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); + var lineStart = ts.getPositionOfLineAndCharacter(file_9, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file_9, i + 1, 0) : file_9.text.length; + var lineContent = file_9.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += lineContent + host.getNewLine(); + context_2 += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context_2 += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += ForegroundColorEscapeSequences.Red; + context_2 += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context_2 += ForegroundColorEscapeSequences.Red; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. var lastCharForLine = i === lastLine ? lastLineChar : undefined; - context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + context_2 += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context_2 += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); } else if (i === lastLine) { - context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + context_2 += lineContent.slice(0, lastLineChar).replace(/./g, "~"); } else { // Squiggle the entire line. - context += lineContent.replace(/./g, "~"); + context_2 += lineContent.replace(/./g, "~"); } - context += resetEscapeSequence; + context_2 += resetEscapeSequence; } output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); output += ":"; @@ -76959,7 +78108,7 @@ var ts; output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); - output += context; + output += context_2; } output += host.getNewLine(); } @@ -77069,21 +78218,19 @@ var ts; oldOptions.baseUrl !== newOptions.baseUrl || !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); } - /** - * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' - * that represent a compilation unit. - * - * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and - * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. - * - * @param rootNames - A set of root files. - * @param options - The compiler options which should be used. - * @param host - The host interacts with the underlying file system. - * @param oldProgram - Reuses an old program structure. - * @param configFileParsingDiagnostics - error during config file parsing - * @returns A 'Program' object. - */ - function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -77111,6 +78258,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -77120,6 +78268,7 @@ var ts; // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; + var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; @@ -77159,6 +78308,23 @@ var ts; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences = projectReferences ? [] : undefined; + var projectReferenceRedirects = ts.createMap(); + if (projectReferences) { + for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { + var ref = projectReferences_1[_i]; + var parsedRef = parseProjectReferenceConfigFile(ref); + resolvedProjectReferences.push(parsedRef); + if (parsedRef) { + if (parsedRef.commandLine.options.outFile) { + var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*packageId*/ undefined); + } + addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + } + } + } var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -77198,8 +78364,8 @@ var ts; // not part of the new program. if (oldProgram && host.onReleaseOldSourceFile) { var oldSourceFiles = oldProgram.getSourceFiles(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); } @@ -77240,6 +78406,7 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -77255,9 +78422,14 @@ var ts; if (commonSourceDirectory === undefined) { var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { - // If a rootDir is specified and is valid use it as the commonSourceDirectory + // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } + else if (options.composite) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } else { commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } @@ -77295,16 +78467,16 @@ var ts; // We only set `file.resolvedModules` via work from the current function, // so it is defined iff we already called the current function on `file`. // That call happened no later than the creation of the `file` object, - // which per above occured during the current program creation. + // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -77435,6 +78607,34 @@ var ts; if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { return oldProgram.structureIsReused = 0 /* Not */; } + // Check if any referenced project tsconfig files are different + var oldRefs = oldProgram.getProjectReferences(); + if (projectReferences) { + if (!oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + for (var i = 0; i < projectReferences.length; i++) { + var oldRef = oldRefs[i]; + if (oldRef) { + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); + if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { + // Resolved project reference has gone missing or changed + return oldProgram.structureIsReused = 0 /* Not */; + } + } + else { + // A previously-unresolved reference may be resolved now + if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } + } + } + else { + if (oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; @@ -77602,6 +78802,7 @@ var ts; } function getEmitHost(writeFileCallback) { return { + getPrependNodes: getPrependNodes, getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, @@ -77615,6 +78816,32 @@ var ts; isEmitBlocked: isEmitBlocked, }; } + function getProjectReferences() { + if (!resolvedProjectReferences) + return; + return resolvedProjectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!resolvedRefOpts.options.outFile) + continue; + var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); + var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var node = ts.createInputFiles(js, dts); + nodes.push(node); + } + } + return nodes; + } function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } @@ -77685,7 +78912,7 @@ var ts; var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -77769,9 +78996,9 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); - // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || - sourceFile.scriptKind === 5 /* External */ || isCheckJs; + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -78147,7 +79374,13 @@ var ts; var sourceFile = getSourceFile(fileName); if (fail) { if (!sourceFile) { - fail(ts.Diagnostics.File_0_not_found, fileName); + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); @@ -78208,31 +79441,45 @@ var ts; // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { - var file_1 = filesByName.get(path); + var file_10 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + if (file_10 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_10.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(fileName, file_10.fileName, refFile, refPos, refEnd); } // If the file was previously found via a node_modules search, but is now being processed as a root file, // then everything it sucks in may also be marked incorrectly, and needs to be checked again. - if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { - sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (file_10 && sourceFilesFoundSearchingNodeModules.get(file_10.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_10.path, false); if (!options.noResolve) { - processReferencedFiles(file_1, isDefaultLib); - processTypeReferenceDirectives(file_1); + processReferencedFiles(file_10, isDefaultLib); + processTypeReferenceDirectives(file_10); } - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); + modulesWithElidedImports.set(file_10.path, false); + processImportedModules(file_10); } // See if we need to reprocess the imports due to prior skipped imports - else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + else if (file_10 && modulesWithElidedImports.get(file_10.path)) { if (currentNodeModulesDepth < maxNodeModuleJsDepth) { - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); + modulesWithElidedImports.set(file_10.path, false); + processImportedModules(file_10); } } - return file_1; + return file_10; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } } // We haven't looked for this file, do so now and cache result var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { @@ -78263,6 +79510,9 @@ var ts; } } filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; @@ -78293,6 +79543,22 @@ var ts; } return file; } + function getProjectReferenceRedirect(fileName) { + var path = toPath(fileName); + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var normalized = ts.getNormalizedAbsolutePath(fileName, path); + var result; + projectReferenceRedirects.forEach(function (v, k) { + if (result !== undefined) { + return undefined; + } + if (normalized.indexOf(k) === 0) { + result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); + } + }); + return result; + } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); @@ -78302,6 +79568,9 @@ var ts; function processTypeReferenceDirectives(file) { // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; @@ -78381,7 +79650,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -78423,9 +79692,9 @@ var ts; function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); + var file_11 = sourceFiles_2[_i]; + if (!file_11.isDeclarationFile) { + fileNames.push(file_11.fileName); } } return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); @@ -78447,6 +79716,27 @@ var ts; } return allFilesBelongToPath; } + function parseProjectReferenceConfigFile(ref) { + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(host, ref); + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + if (sourceFile === undefined) { + return undefined; + } + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + return { commandLine: commandLine, sourceFile: sourceFile }; + } + function addProjectReferenceRedirects(referencedProject, target) { + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); + target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); + } + function getDeclarationOutputDirectory(proj) { + return proj.options.declarationDir || + proj.options.outDir || + ts.getDirectoryPath(proj.options.configFilePath); + } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !options.strictNullChecks) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); @@ -78476,6 +79766,48 @@ var ts; if (options.paths && options.baseUrl === undefined) { createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + if (projectReferences) { + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; + if (resolvedRefOpts === undefined) { + createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); + continue; + } + if (!resolvedRefOpts.composite) { + createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + if (ref.prepend) { + if (resolvedRefOpts.outFile) { + if (!host.fileExists(resolvedRefOpts.outFile)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + } + } + else { + createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + } + } + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite && rootNames.length < files.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); + var _loop_10 = function (file_12) { + if (normalizedRootNames.every(function (r) { return r !== file_12; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file_12)); + } + }; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var file_12 = sourceFiles_4[_i]; + _loop_10(file_12); + } + } if (options.paths) { for (var key in options.paths) { if (!ts.hasProperty(options.paths, key)) { @@ -78567,6 +79899,11 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified @@ -78679,12 +80016,15 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); } } - function getOptionPathsSyntax() { + function getOptionsSyntaxByName(name) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); if (compilerOptionsObjectLiteralSyntax) { - return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); } - return ts.emptyArray; + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; } function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); @@ -78692,6 +80032,15 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } + function createDiagnosticForReference(index, message, arg0, arg1) { + var referencesSyntax = getProjectReferencesSyntax(); + if (referencesSyntax) { + if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { + return; + } + } + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || @@ -78700,11 +80049,28 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } + function getProjectReferencesSyntax() { + if (_referencesArrayLiteralSyntax === undefined) { + _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword + if (options.configFile) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isArrayLiteralExpression(prop.initializer)) { + _referencesArrayLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _referencesArrayLiteralSyntax; + } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile && options.configFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { var prop = _a[_i]; if (ts.isObjectLiteralExpression(prop.initializer)) { _compilerOptionsObjectLiteralSyntax = prop.initializer; @@ -78723,6 +80089,13 @@ var ts; } return !!props.length; } + function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { + if (arrayLiteral.elements.length <= index) { + // Out-of-bounds + return false; + } + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -78759,6 +80132,27 @@ var ts; } ts.createProgram = createProgram; /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + /** + * Returns the target config filename of a project reference + */ + function resolveProjectReferencePath(host, ref) { + if (!host.fileExists(ref.path)) { + return ts.combinePaths(ref.path, "tsconfig.json"); + } + return ref.path; + } + /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. @@ -78769,6 +80163,7 @@ var ts; switch (extension) { case ".ts" /* Ts */: case ".d.ts" /* Dts */: + case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check // These are always allowed. return undefined; case ".tsx" /* Tsx */: @@ -78969,6 +80364,7 @@ var ts; * Get all the dependencies of the sourceFile */ function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; var compilerOptions = programOfThisState.getCompilerOptions(); // With --out or --outFile all outputs go into single file, all files depend on each other if (compilerOptions.outFile || compilerOptions.out) { @@ -78988,7 +80384,7 @@ var ts; var references = state.referencedMap.get(path); if (references) { var iterator = references.keys(); - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { queue.push(value); } } @@ -78998,7 +80394,6 @@ var ts; var file = programOfThisState.getSourceFileByPath(path); return file ? file.fileName : path; })); - var _b; } BuilderState.getAllDependencies = getAllDependencies; /** @@ -79443,8 +80838,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_1 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -79522,6 +80917,7 @@ var ts; startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, @@ -79694,6 +81090,10 @@ var ts; function resolveModuleNames(moduleNames, containingFile, reusedNames) { return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } @@ -79741,17 +81141,19 @@ var ts; return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } // Use some ancestor of the root directory + var subDirectory; if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { var parentPath = ts.getDirectoryPath(dirPath); if (parentPath === dirPath) { break; } + subDirectory = dirPath.slice(parentPath.length + ts.directorySeparator.length); dirPath = parentPath; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath, subDirectory: subDirectory }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -79771,7 +81173,7 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { // If the failed lookup location path is not one of the supported extensions, // store it in the custom path @@ -79783,7 +81185,7 @@ var ts; setAtRoot = true; } else { - setDirectoryWatcher(dir, dirPath); + setDirectoryWatcher(dir, dirPath, subDirectory); } } } @@ -79791,13 +81193,19 @@ var ts; setDirectoryWatcher(rootDir, rootPath); } } - function setDirectoryWatcher(dir, dirPath) { + function setDirectoryWatcher(dir, dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { dirWatcher.refCount++; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }; + directoryWatchesOfFailedLookups.set(dirPath, dirWatcher); + } + if (subDirectory) { + var subDirectoryMap = dirWatcher.subDirectoryMap || (dirWatcher.subDirectoryMap = ts.createMap()); + var existing = subDirectoryMap.get(subDirectory) || 0; + subDirectoryMap.set(subDirectory, existing + 1); } } function stopWatchFailedLookupLocationOfResolution(resolution) { @@ -79813,7 +81221,7 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { @@ -79829,7 +81237,7 @@ var ts; removeAtRoot = true; } else { - removeDirectoryWatcher(dirPath); + removeDirectoryWatcher(dirPath, subDirectory); } } } @@ -79837,22 +81245,40 @@ var ts; removeDirectoryWatcher(rootPath); } } - function removeDirectoryWatcher(dirPath) { + function removeDirectoryWatcher(dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (subDirectory) { + var existing = dirWatcher.subDirectoryMap.get(subDirectory); + if (existing === 1) { + dirWatcher.subDirectoryMap.delete(subDirectory); + } + else { + dirWatcher.subDirectoryMap.set(subDirectory, existing - 1); + } + } // Do not close the watcher yet since it might be needed by other failed lookup locations. dirWatcher.refCount--; } + function inWatchedSubdirectory(dirPath, fileOrDirectoryPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (!dirWatcher || !dirWatcher.subDirectoryMap) + return false; + return ts.forEachKey(dirWatcher.subDirectoryMap, function (subDirectory) { + var fullSubDirectory = dirPath + "/" + subDirectory; + return fullSubDirectory === fileOrDirectoryPath || isInDirectoryPath(fullSubDirectory, fileOrDirectoryPath); + }); + } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // If the files are added to project root or node_modules directory, always run through the invalidation process // Otherwise run through invalidation only if adding to the immediate directory if (!allFilesHaveInvalidatedResolution && - dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + (dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath || inWatchedSubdirectory(dirPath, fileOrDirectoryPath))) { if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { resolutionHost.onInvalidatedResolution(); } @@ -79976,7 +81402,7 @@ var ts; return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // For now just recompile @@ -80112,34 +81538,11 @@ var ts; function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; - var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - /** - * Reads the config file, reports errors if any and exits if the config file cannot be found - */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - var result = ts.parseJsonText(configFileName, configFileText); - var cwd = host.getCurrentDirectory(); - return ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); - } - ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ @@ -80221,12 +81624,12 @@ var ts; watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, setTimeout: system.setTimeout ? (function (callback, ms) { + var _a; var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - var _a; }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, trace: function (s) { return system.write(s); }, @@ -80986,6 +82389,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, { name: "removeComments", type: "boolean", @@ -81246,6 +82656,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, { name: "listFiles", type: "boolean", @@ -81539,11 +82955,13 @@ var ts; function parseCommandLine(commandLine, readFile) { var options = {}; var fileNames = []; + var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, + projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -81656,6 +83074,29 @@ var ts; } return optionNameMap.get(optionName); } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -81703,55 +83144,67 @@ var ts; var _tsconfigRootOptions; function getTsconfigRootOptionsMap() { if (_tsconfigRootOptions === undefined) { - _tsconfigRootOptions = commandLineOptionsToMap([ - { - name: "compilerOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 - }, - { - name: "typingOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "typeAcquisition", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "extends", - type: "string" - }, - { - name: "files", - type: "list", - element: { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { name: "files", - type: "string" - } - }, - { - name: "include", - type: "list", - element: { + type: "list", + element: { + name: "files", + type: "string" + } + }, + { name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { + type: "list", + element: { + name: "include", + type: "string" + } + }, + { name: "exclude", - type: "string" - } - }, - ts.compileOnSaveCommandLineOption - ]); + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; } return _tsconfigRootOptions; } @@ -81759,20 +83212,25 @@ var ts; * Convert the json syntax tree into the json value */ function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } ts.convertToObject = convertToObject; /** - * Convert the json syntax tree into the json value + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined */ - function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.jsonObject) { - return {}; + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, - /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined); function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { - var result = {}; + var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; if (element.kind !== 269 /* PropertyAssignment */) { @@ -81792,11 +83250,13 @@ var ts; } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { - result[keyText] = value; + if (returnValue) { + result[keyText] = value; + } // Notify key value set, if user asked for it if (jsonConversionNotifier && // Current callbacks are only on known parent option or if we are setting values in the root - (parentOption || knownOptions === knownRootOptions)) { + (parentOption || isRootOptionMap(knownOptions))) { var isValidOptionValue = isCompilerOptionsValue(option, value); if (parentOption) { if (isValidOptionValue) { @@ -81804,7 +83264,7 @@ var ts; jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); } } - else if (knownOptions === knownRootOptions) { + else if (isRootOptionMap(knownOptions)) { if (isValidOptionValue) { // Notify about the valid root key value being set jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); @@ -81820,7 +83280,7 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -81895,6 +83355,7 @@ var ts; return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } + ts.convertToObjectWorker = convertToObjectWorker; function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : @@ -81944,7 +83405,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_9 = function (name) { + var _loop_11 = function (name) { if (ts.hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean @@ -81973,7 +83434,7 @@ var ts; } }; for (var name in options) { - _loop_9(name); + _loop_11(name); } return result; } @@ -82123,12 +83584,13 @@ var ts; var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); - options.configFilePath = configFileName; + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; return { options: options, fileNames: fileNames, + projectReferences: projectReferences, typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), raw: raw, errors: errors, @@ -82167,19 +83629,43 @@ var ts; createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } - else { - var outDir = raw.compilerOptions && raw.compilerOptions.outDir; - if (outDir) { - excludeSpecs = [outDir]; + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); } } if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + var references = []; + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + references.push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + result.projectReferences = references; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } return result; } function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { @@ -82297,7 +83783,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -82332,6 +83818,7 @@ var ts; return extendedConfigPath; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -82360,7 +83847,6 @@ var ts; mapPropertiesInRawIfNotUndefined("files"); } return extendedConfig; - var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { @@ -82385,7 +83871,7 @@ var ts; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function getDefaultCompilerOptions(configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {}; return options; @@ -82393,10 +83879,13 @@ var ts; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -82557,7 +84046,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -82591,37 +84080,41 @@ var ts; if (filesSpecs) { for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { var fileName = filesSpecs_1[_i]; - var file = ts.getNormalizedAbsolutePath(fileName, basePath); - literalFileMap.set(keyMapper(file), file); + var file_13 = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file_13), file_13); } } if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var file_14 = _b[_a]; // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // // This handles cases where we may encounter both .ts and // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. - if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + if (hasFileWithHigherPriorityExtension(file_14, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the // "include" array. If there is a lower priority extension in the // same directory, we should remove it. - removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); - var key = keyMapper(file); + removeWildcardFilesWithLowerPriorityExtension(file_14, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file_14); if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { - wildcardFileMap.set(key, file); + wildcardFileMap.set(key, file_14); } } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { + return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); + }); return { fileNames: literalFiles.concat(wildcardFiles), + projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -82636,20 +84129,10 @@ var ts; return diag === undefined; }); function createDiagnostic(message, spec) { - if (jsonSourceFile && jsonSourceFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { - var property = _a[_i]; - if (ts.isArrayLiteralExpression(property.initializer)) { - for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (ts.isStringLiteral(element) && element.text === spec) { - return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); - } - } - } - } - } - return ts.createCompilerDiagnostic(message, spec); + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); } } function specToDiagnostic(spec, allowTrailingRecursion) { @@ -82682,8 +84165,8 @@ var ts; if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { - var file = include_1[_i]; - var spec = ts.normalizePath(ts.combinePaths(path, file)); + var file_15 = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file_15)); if (excludeRegex && excludeRegex.test(spec)) { continue; } @@ -82877,6 +84360,17 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + /** Single or multi-line comments */ + OutliningSpanKind["Comment"] = "comment"; + /** Sections marked by '// #region' and '// #endregion' comments */ + OutliningSpanKind["Region"] = "region"; + /** Declarations and expressions */ + OutliningSpanKind["Code"] = "code"; + /** Contiguous blocks of import declarations */ + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); var OutputFileType; (function (OutputFileType) { OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; @@ -82972,6 +84466,8 @@ var ts; * */ ScriptElementKind["jsxAttribute"] = "JSX attribute"; + /** String literal */ + ScriptElementKind["string"] = "string"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -83077,7 +84573,7 @@ var ts; case 236 /* TypeAliasDeclaration */: case 165 /* TypeLiteral */: return 2 /* Type */; - case 292 /* JSDocTypedefTag */: + case 296 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; case 272 /* EnumMember */: @@ -83131,6 +84627,10 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName return 2 /* Type */; } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } else { return 1 /* Value */; } @@ -83193,6 +84693,8 @@ var ts; switch (node.parent.kind) { case 161 /* TypeReference */: return true; + case 178 /* ImportType */: + return !node.parent.isTypeOf; case 206 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } @@ -83280,7 +84782,7 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 292 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(node)) { // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. // Then we get parent again in the loop. @@ -83318,7 +84820,10 @@ var ts; case 204 /* ClassExpression */: return "class" /* classElement */; case 235 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 236 /* TypeAliasDeclaration */: return "type" /* typeElement */; + case 236 /* TypeAliasDeclaration */: + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + return "type" /* typeElement */; case 237 /* EnumDeclaration */: return "enum" /* enumElement */; case 231 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); @@ -83349,8 +84854,6 @@ var ts; case 251 /* ExportSpecifier */: case 245 /* NamespaceImport */: return "alias" /* alias */; - case 292 /* JSDocTypedefTag */: - return "type" /* typeElement */; case 199 /* BinaryExpression */: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; @@ -83412,6 +84915,10 @@ var ts; return startEndContainsRange(r1.pos, r1.end, r2); } ts.rangeContainsRange = rangeContainsRange; + function rangeContainsPosition(r, pos) { + return r.pos <= pos && pos <= r.end; + } + ts.rangeContainsPosition = rangeContainsPosition; function startEndContainsRange(start, end, range) { return start <= range.pos && end >= range.end; } @@ -83678,7 +85185,7 @@ var ts; return findPrecedingToken(position, file); } ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { + function findNextToken(previousToken, parent, sourceFile) { return find(parent); function find(n) { if (ts.isToken(n) && n.pos === previousToken.end) { @@ -83693,7 +85200,7 @@ var ts; (child.pos <= previousToken.pos && child.end > previousToken.end) || // previous token ends exactly at the beginning of child (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { + if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) { return find(child); } } @@ -83724,11 +85231,11 @@ var ts; if (position < child.end) { var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || // cursor in the leading trivia - !nodeHasTokens(child) || + !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } else { @@ -83743,7 +85250,7 @@ var ts; // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } } @@ -83757,19 +85264,19 @@ var ts; return n; } var children = n.getChildren(sourceFile); - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } /** * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. */ - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { var child = children[i]; if (isWhiteSpaceOnlyJsxText(child)) { ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); } - else if (nodeHasTokens(children[i])) { + else if (nodeHasTokens(children[i], sourceFile)) { return children[i]; } } @@ -83881,22 +85388,22 @@ var ts; remainingLessThanTokens++; break; case 18 /* CloseBraceToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); if (!token) return false; break; case 20 /* CloseParenToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); if (!token) return false; break; case 22 /* CloseBracketToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); if (!token) return false; @@ -83950,10 +85457,10 @@ var ts; } } ts.hasDocComment = hasDocComment; - function nodeHasTokens(n) { + function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth() !== 0; + return n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.getCombinedModifierFlags(node); @@ -84050,11 +85557,6 @@ var ts; return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); @@ -84077,6 +85579,10 @@ var ts; return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createTextRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { return createTextChange(ts.createTextSpan(start, length), newText); } @@ -84109,7 +85615,6 @@ var ts; return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; - /** Returns `true` the first time it encounters a node and `false` afterwards. */ function nodeSeenTracker() { var seen = []; return function (node) { @@ -84157,6 +85662,63 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + } + ts.makeImport = makeImport; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default" /* Default */) { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { + // See GH#16922 + ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); + return propSymbol.target; + } + return propSymbol; + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -84489,20 +86051,20 @@ var ts; * user was before extracting it. */ /* @internal */ - function getRenameLocation(edits, renameFilename, name, isDeclaredBeforeUse) { + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { var delta = 0; var lastPos = -1; for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; ts.Debug.assert(fileName === renameFilename); - for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { - var change = textChanges_2[_b]; + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; var span = change.span, newText = change.newText; var index = newText.indexOf(name); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. - if (!isDeclaredBeforeUse) { + if (!preferLastLocation) { return lastPos; } } @@ -84510,7 +86072,7 @@ var ts; } } // If the declaration comes first, return the position of the last occurrence. - ts.Debug.assert(isDeclaredBeforeUse); + ts.Debug.assert(preferLastLocation); ts.Debug.assert(lastPos >= 0); return lastPos; } @@ -85158,20 +86720,22 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 288 /* JSDocParameterTag */: + case 292 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); + pos = tag.end; break; - case 290 /* JSDocTypeTag */: + case 294 /* JSDocTypeTag */: processElement(tag.typeExpression); + pos = tag.end; break; - case 289 /* JSDocReturnTag */: + case 293 /* JSDocReturnTag */: processElement(tag.typeExpression); + pos = tag.end; break; } - pos = tag.end; } } if (pos !== docComment.end) { @@ -85413,7 +86977,7 @@ var ts; var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = ts.getSupportedExtensions(compilerOptions); + var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); } @@ -85426,6 +86990,12 @@ var ts; return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json" /* Json */) : + extensions; + } /** * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option @@ -85464,13 +87034,16 @@ var ts; * Remove the basename from the path. Note that we don't use the basename to filter completions; * the client is responsible for refining completions. */ - fragment = ts.getDirectoryPath(fragment); + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } if (fragment === "") { fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); - var baseDirectory = ts.getDirectoryPath(absolutePath); + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (tryDirectoryExists(host, baseDirectory)) { // Enumerate the available files if possible @@ -85489,7 +87062,7 @@ var ts; if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; } - var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } @@ -85502,8 +87075,8 @@ var ts; var directories = tryGetDirectories(host, baseDirectory); if (directories) { for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var directory = directories_1[_a]; - var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + var directory_2 = directories_1[_a]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory_2)); if (directoryName !== "@types") { result.push(nameAndKind(directoryName, "directory" /* directory */)); } @@ -85522,7 +87095,7 @@ var ts; function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); @@ -85530,7 +87103,7 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_10 = function (name, kind) { + var _loop_12 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind)); @@ -85538,12 +87111,12 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_10(name, kind); + _loop_12(name, kind); } } } } - var fragmentDirectory = containsSlash(fragment) ? ts.getDirectoryPath(fragment) : undefined; + var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { var ambientName = _d[_c]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); @@ -85554,7 +87127,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_11 = function (moduleName) { + var _loop_13 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); @@ -85562,7 +87135,7 @@ var ts; }; for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { var moduleName = _f[_e]; - _loop_11(moduleName); + _loop_13(moduleName); } } if (!foundGlobal) { @@ -85598,12 +87171,13 @@ var ts; } // The prefix has two effective parts: the directory path and the base component after the filepath that is not a // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); var fragmentHasPath = containsSlash(fragment); + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); @@ -85764,15 +87338,6 @@ var ts; } return false; } - function normalizeAndPreserveTrailingSlash(path) { - if (ts.normalizeSlashes(path) === "./") { - // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case. - // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning. - return ""; - } - var norm = ts.normalizePath(path); - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; - } /** * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment @@ -85892,7 +87457,7 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); }); + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: @@ -86459,11 +88024,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 275 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 277 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 293 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 297 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -86599,12 +88164,8 @@ var ts; } else if (isRightOfOpenTag) { var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); - if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 /* Value */ | 2097152 /* Alias */)); })); - } - else { - symbols = tagSymbols; - } + tryGetGlobalSymbols(); + symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; } else if (isStartingCloseTag) { @@ -86628,11 +88189,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 288 /* JSDocParameterTag */: - case 293 /* JSDocPropertyTag */: - case 289 /* JSDocReturnTag */: - case 290 /* JSDocTypeTag */: - case 292 /* JSDocTypedefTag */: + case 292 /* JSDocParameterTag */: + case 297 /* JSDocPropertyTag */: + case 293 /* JSDocReturnTag */: + case 294 /* JSDocTypeTag */: + case 296 /* JSDocTypedefTag */: return true; } } @@ -86894,7 +88455,7 @@ var ts; var exportedSymbols = typeChecker.getExportsOfModule(symbol); // If the exported symbols contains type, // symbol can be referenced at locations where type is allowed - return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); + return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); } } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { @@ -87670,7 +89231,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 294 /* SyntaxList */: + case 298 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -87707,6 +89268,9 @@ var ts; } function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { + case ".": + case "@": + return true; case '"': case "'": case "`": @@ -87715,8 +89279,12 @@ var ts; case "<": // Opening JSX tag return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */; + case "/": + return ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); default: - return ts.Debug.fail(triggerCharacter); + return ts.Debug.assertNever(triggerCharacter); } } function isStringLiteralOrTemplate(node) { @@ -87811,6 +89379,10 @@ var ts; case 125 /* GetKeyword */: case 136 /* SetKeyword */: return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]); + case 121 /* AwaitKeyword */: + return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); + case 120 /* AsyncKeyword */: + return highlightSpans(getAsyncAndAwaitOccurrences(node)); default: return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) @@ -88058,6 +89630,29 @@ var ts; }); return keywords; } + function getAsyncAndAwaitOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + if (func.modifiers) { + func.modifiers.forEach(function (modifier) { + pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */); + }); + } + ts.forEachChild(func, aggregate); + return keywords; + function aggregate(node) { + if (ts.isAwaitExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */); + } + // Do not cross function boundaries. + if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) { + ts.forEachChild(node, aggregate); + } + } + } function getIfElseOccurrences(ifStatement, sourceFile) { var keywords = getIfElseKeywords(ifStatement, sourceFile); var result = []; @@ -88178,9 +89773,10 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); entry = { sourceFile: sourceFile, languageServiceRefCount: 1, @@ -88309,6 +89905,8 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; + case 71 /* Identifier */: // for 'const x = require("y"); + break; // TODO: GH#23879 case 242 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */)); break; @@ -88338,6 +89936,11 @@ var ts; directImports.push(direct); } break; + case 178 /* ImportType */: + directImports.push(direct); + break; + default: + ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); } } } @@ -88415,6 +90018,14 @@ var ts; return; } if (decl.kind === 178 /* ImportType */) { + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); + } return; } // Ignore if there's a grammar error @@ -88442,7 +90053,7 @@ var ts; var name = importClause.name; // If a default import has the same name as the default export, allow to rename it. // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. - if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { + if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { var defaultImportAlias = checker.getSymbolAtLocation(name); addSearch(name, defaultImportAlias); } @@ -88500,24 +90111,18 @@ var ts; function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { - if (statement.kind !== 249 /* ExportDeclaration */) + if (!ts.isExportDeclaration(statement)) return; - var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier; - if (moduleSpecifier || !exportClause) - return; - for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) { - var element = _b[_i]; - if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) { - return true; - } - } + var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; + return !moduleSpecifier && exportClause && + exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; }); }); } function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var referencingFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var referencingFile = sourceFiles_5[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 273 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -88547,8 +90152,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -88653,6 +90258,9 @@ var ts; else if (ts.isBinaryExpression(parent.parent)) { return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); } + else if (ts.isJSDocTypedefTag(parent)) { + return exportInfo(symbol, 0 /* Named */); + } } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. @@ -88697,7 +90305,7 @@ var ts; // If the import has a different name than the export, do not continue searching. // If `importedName` is undefined, do continue searching as the export is anonymous. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) - var importedName = symbolName(importedSymbol); + var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } @@ -88764,15 +90372,6 @@ var ts; return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; } FindAllReferences.getExportInfo = getExportInfo; - function symbolName(symbol) { - if (symbol.escapedName !== "default" /* Default */) { - return symbol.escapedName; - } - return ts.forEach(symbol.declarations, function (decl) { - var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ && name.escapedText; - }); - } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. @@ -88847,9 +90446,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 270 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -88882,8 +90481,8 @@ var ts; case "symbol": { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_3 = def.node; @@ -88891,13 +90490,13 @@ var ts; } case "keyword": { var node_4 = def.node; - var name_5 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; + var name_4 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } case "this": { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { @@ -89010,7 +90609,7 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -89025,32 +90624,36 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } - if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { - return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet); + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + node = undefined; } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function isModuleReferenceLocation(node) { - if (!ts.isStringLiteralLike(node)) { - return false; - } - switch (node.parent.kind) { - case 238 /* ModuleDeclaration */: - case 253 /* ExternalModuleReference */: - case 243 /* ImportDeclaration */: - case 249 /* ExportDeclaration */: - return true; - case 186 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent); - default: - return false; - } + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile); } - function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) { + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); - var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. return { type: "node", node: reference.literal }; } else { @@ -89073,10 +90676,11 @@ var ts; } break; default: + // This may be merged with something. ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; + return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -89104,17 +90708,17 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; - var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); - if (node.kind === 79 /* DefaultKeyword */) { + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + if (node && node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -89160,7 +90764,6 @@ var ts; return ts.firstDefined(symbol.declarations, function (decl) { if (!decl.parent) { // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. - ts.Debug.assert(decl.kind === 273 /* SourceFile */); ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol)); } return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) @@ -89234,7 +90837,7 @@ var ts; // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** @@ -89278,10 +90881,8 @@ var ts; var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; - // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - if (!(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) { + if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); - } } } // For each import, find all references to that import in its source file. @@ -89310,6 +90911,17 @@ var ts; } } } + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -89333,22 +90945,14 @@ var ts; var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */); if (bindingElement && bindingElement.parent.kind === 179 /* ObjectBindingPattern */ && + ts.isIdentifier(bindingElement.name) && !bindingElement.propertyName) { return bindingElement; } } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - if (!bindingElement) - return undefined; - var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { - // See GH#16922 - ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); - return propSymbol.target; - } - return propSymbol; + return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); } /** * Determines the smallest scope in which a symbol may have named references. @@ -89519,6 +91123,9 @@ var ts; getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } + function hasMatchingMeaning(referenceLocation, state) { + return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (!isValidReferencePosition(referenceLocation, search.text)) { @@ -89534,9 +91141,8 @@ var ts; } return; } - if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) { + if (!hasMatchingMeaning(referenceLocation, state)) return; - } var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); if (!referenceSymbol) { return; @@ -90197,7 +91803,9 @@ var ts; var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. - return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) + return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) || + // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); }) ? [sigInfo] : [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node)); } @@ -90252,14 +91860,14 @@ var ts; function getReferenceAtPosition(sourceFile, position, program) { var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { - var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); - return file && { fileName: referencePath.fileName, file: file }; + var file_16 = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file_16 && { fileName: referencePath.fileName, file: file_16 }; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - var file = reference && program.getSourceFile(reference.resolvedFileName); - return file && { fileName: typeReferenceDirective.fileName, file: file }; + var file_17 = reference && program.getSourceFile(reference.resolvedFileName); + return file_17 && { fileName: typeReferenceDirective.fileName, file: file_17 }; } return undefined; } @@ -90431,6 +92039,7 @@ var ts; "author", "argument", "borrows", + "callback", "class", "constant", "constructor", @@ -90495,10 +92104,12 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 293 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: + case 297 /* JSDocPropertyTag */: return [declaration]; - case 292 /* JSDocTypedefTag */: - return [declaration.parent]; + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); } @@ -90518,15 +92129,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 286 /* JSDocAugmentsTag */: + case 289 /* JSDocAugmentsTag */: return withNode(tag.class); - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 290 /* JSDocTypeTag */: + case 294 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 292 /* JSDocTypedefTag */: - case 293 /* JSDocPropertyTag */: - case 288 /* JSDocParameterTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + case 297 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -90851,12 +92463,42 @@ var ts; JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ JsTyping.nodeCoreModuleList = [ - "buffer", "querystring", "events", "http", "cluster", - "zlib", "os", "https", "punycode", "repl", "readline", - "vm", "child_process", "url", "dns", "net", - "dgram", "fs", "path", "string_decoder", "tls", - "crypto", "stream", "util", "assert", "tty", "domain", - "constants", "process", "v8", "timers", "console" + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" ]; /* @internal */ JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); @@ -90915,8 +92557,8 @@ var ts; getTypingNamesFromSourceFileNames(fileNames); // add typings for unresolved imports if (unresolvedImports) { - var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); - addInferredTypings(module, "Inferred typings from unresolved imports"); + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); } // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach(function (typing, name) { @@ -91013,8 +92655,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -91114,7 +92756,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_12 = function (sourceFile) { + var _loop_14 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -91124,9 +92766,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; - _loop_12(sourceFile); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + _loop_14(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -91503,7 +93145,7 @@ var ts; if (ts.hasJSDocNodes(node)) { ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 292 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(tag)) { addLeafNode(tag); } }); @@ -91578,6 +93220,7 @@ var ts; } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { + var _a; target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); if (source.additionalNodes) { @@ -91588,7 +93231,6 @@ var ts; mergeChildren(target.children); sortChildren(target.children); } - var _a; } /** Recursively ensure that each NavNode's children are in sorted order. */ function sortChildren(children) { @@ -91616,8 +93258,6 @@ var ts; case 192 /* ArrowFunction */: case 204 /* ClassExpression */: return getFunctionOrClassName(node); - case 292 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return undefined; } @@ -91659,29 +93299,10 @@ var ts; return "()"; case 159 /* IndexSignature */: return "[]"; - case 292 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return ""; } } - function getJSDocTypedefTagName(node) { - if (node.name) { - return node.name.text; - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 213 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71 /* Identifier */) { - return nameIdentifier.text; - } - } - } - return ""; - } - } /** Flattens the NavNode tree to a list, keeping only the top-level items. */ function topLevelItems(root) { var topLevel = []; @@ -91707,7 +93328,8 @@ var ts; case 238 /* ModuleDeclaration */: case 273 /* SourceFile */: case 236 /* TypeAliasDeclaration */: - case 292 /* JSDocTypedefTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: return true; case 154 /* Constructor */: case 153 /* MethodDeclaration */: @@ -91870,17 +93492,23 @@ var ts; */ function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(topLevelImportDecls); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; var ambientModuleBody = getModuleBlock(ambientModule); var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(ambientModuleImportDecls); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); - function organizeImportsWorker(oldImportDecls) { + function organizeImportsWorker(oldImportDecls, coalesce) { if (ts.length(oldImportDecls) === 0) { return; } @@ -91894,7 +93522,7 @@ var ts; var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + ? coalesce(importGroup) : importGroup; }); // Delete or replace the first import. @@ -91969,7 +93597,9 @@ var ts; } } function getExternalModuleName(specifier) { - return ts.isStringLiteralLike(specifier) ? specifier.text : undefined; + return specifier !== undefined && ts.isStringLiteralLike(specifier) + ? specifier.text + : undefined; } /* @internal */ // Internal for testing /** @@ -92015,15 +93645,14 @@ var ts; } } newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); - var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { - return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || - compareIdentifiers(s1.name, s2.name); - }); + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); @@ -92069,23 +93698,77 @@ var ts; namedImports: namedImports, }; } - function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); - } } OrganizeImports.coalesceImports = coalesceImports; + /* @internal */ // Internal for testing + /** + * @param exportGroup a list of ExportDeclarations, all with the same module name. + */ + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + /* + * Returns entire export declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + */ + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + // Only the first such export is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); + } /* internal */ // Exported for testing function compareModuleSpecifiers(m1, m2) { var name1 = getExternalModuleName(m1); var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); /* @internal */ @@ -92095,7 +93778,7 @@ var ts; var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) { + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); if (newPath !== undefined) { @@ -92107,25 +93790,16 @@ var ts; } ts.getEditsForFileRename = getEditsForFileRename; function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var cfg = program.getCompilerOptions().configFile; - if (!cfg) - return; - var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath); + var configFile = program.getCompilerOptions().configFile; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); if (oldFile) { - changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath); + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); } } - function getFilesEntry(cfg, fileName) { - var filesProp = ts.find(cfg.properties, function (prop) { - return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; - }); - var files = filesProp && filesProp.initializer; - return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined; - } function isRef(toUpdate) { return "fileName" in toUpdate; } - function getImportsToUpdate(program, oldFilePath) { + function getImportsToUpdate(program, oldFilePath, host) { var checker = program.getTypeChecker(); var result = []; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { @@ -92141,8 +93815,10 @@ var ts; // If it resolved to something already, ignore. if (checker.getSymbolAtLocation(importStringLiteral)) continue; - var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (ts.contains(resolved.failedLookupLocations, oldFilePath)) { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); } } @@ -92151,11 +93827,11 @@ var ts; } function getPathUpdater(oldFilePath, newFilePath, host) { // Get the relative path from old to new location, and append it on to the end of imports and normalize. - var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); return function (oldPath) { if (!ts.pathIsRelative(oldPath)) return; - return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); }; } function createStringRange(node, sourceFile) { @@ -92176,7 +93852,27 @@ var ts; OutliningElementsCollector.collectElements = collectElements; function addNodeOutliningSpans(sourceFile, cancellationToken, out) { var depthRemaining = 40; - sourceFile.forEachChild(function walk(n) { + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + } + } + function visitNonImportNode(n) { if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); @@ -92189,17 +93885,17 @@ var ts; depthRemaining--; if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { // Consider an 'else if' to be on the same depth as the 'if'. - walk(n.expression); - walk(n.thenStatement); + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); depthRemaining++; - walk(n.elseStatement); + visitNonImportNode(n.elseStatement); depthRemaining--; } else { - n.forEachChild(walk); + n.forEachChild(visitNonImportNode); } depthRemaining++; - }); + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -92214,7 +93910,7 @@ var ts; } if (!result[1]) { var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); - regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region")); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region")); } else { var region = regions.pop(); @@ -92248,7 +93944,7 @@ var ts; break; case 3 /* MultiLineCommentTrivia */: combineAndAddMultipleSingleLineComments(); - out.push(createOutliningSpanFromBounds(pos, end)); + out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */)); singleLineCommentCount = 0; break; default: @@ -92259,12 +93955,12 @@ var ts; function combineAndAddMultipleSingleLineComments() { // Only outline spans of two or more consecutive single line comments if (singleLineCommentCount > 1) { - out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */)); } } } - function createOutliningSpanFromBounds(pos, end) { - return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { @@ -92298,7 +93994,7 @@ var ts; default: // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. - return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } case 239 /* ModuleBlock */: return spanForNode(n.parent); @@ -92330,14 +94026,14 @@ var ts; return undefined; } var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); - return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { if (hintSpan === void 0) { hintSpan = textSpan; } if (autoCollapse === void 0) { autoCollapse = false; } if (bannerText === void 0) { bannerText = "..."; } - return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); @@ -92620,13 +94316,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_13 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_4 = _loop_13(start); + var state_4 = _loop_15(start); if (typeof state_4 === "object") return state_4.value; } @@ -93172,6 +94868,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } + // Can't rename a module name. + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -93291,7 +94990,7 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_14 = function (declaration) { + var _loop_16 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -93305,7 +95004,7 @@ var ts; }; for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { var declaration = declarations_12[_b]; - var state_5 = _loop_14(declaration); + var state_5 = _loop_16(declaration); if (typeof state_5 === "object") return state_5.value; } @@ -93652,7 +95351,9 @@ var ts; program.getSemanticDiagnostics(sourceFile); var checker = program.getDiagnosticsProducingTypeChecker(); var diags = []; - if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))) { + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJavaScript(sourceFile); @@ -93694,16 +95395,39 @@ var ts; var name = importNameForConvertToDefaultImport(importNode); if (!name) continue; - var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); } } } - return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 213 /* VariableStatement */: + return statement.declarationList.declarations.some(function (decl) { + return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 215 /* ExpressionStatement */: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + var kind = ts.getSpecialPropertyAssignmentKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } function importNameForConvertToDefaultImport(node) { switch (node.kind) { case 243 /* ImportDeclaration */: @@ -94434,7 +96158,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_15 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -94453,7 +96177,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_15(opt); + _loop_17(opt); } return options; } @@ -94857,6 +96581,7 @@ var ts; rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. @@ -95317,6 +97042,9 @@ var ts; function isArrowFunctionContext(context) { return context.contextNode.kind === 192 /* ArrowFunction */; } + function isImportTypeContext(context) { + return context.contextNode.kind === 178 /* ImportType */; + } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; } @@ -95439,18 +97167,18 @@ var ts; // This array is used only during construction of the rulesbucket in the map var rulesBucketConstructionStateList = new Array(map.length); for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { - var rule = rules_1[_i]; - var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; - for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var rule_1 = rules_1[_i]; + var specificRule = rule_1.leftTokenRange.isSpecific && rule_1.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule_1.leftTokenRange.tokens; _a < _b.length; _a++) { var left = _b[_a]; - for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + for (var _c = 0, _d = rule_1.rightTokenRange.tokens; _c < _d.length; _c++) { var right = _d[_c]; var index = getRuleBucketIndex(left, right); var rulesBucket = map[index]; if (rulesBucket === undefined) { rulesBucket = map[index] = []; } - addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); + addRule(rulesBucket, rule_1.rule, specificRule, rulesBucketConstructionStateList, index); } } } @@ -96757,7 +98485,7 @@ var ts; NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; })(NextTokenKind || (NextTokenKind = {})); function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { - var nextToken = ts.findNextToken(precedingToken, current); + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); if (!nextToken) { return 0 /* Unknown */; } @@ -96806,9 +98534,10 @@ var ts; } function getContainingList(node, sourceFile) { if (node.parent) { + var end = node.end; switch (node.parent.kind) { case 161 /* TypeReference */: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); case 183 /* ObjectLiteralExpression */: return node.parent.properties; case 182 /* ArrayLiteralExpression */: @@ -96823,22 +98552,25 @@ var ts; case 163 /* ConstructorType */: case 158 /* ConstructSignature */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || + getListIfStartEndIsInListRange(node.parent.parameters, start, end); } case 234 /* ClassDeclaration */: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); case 187 /* NewExpression */: case 186 /* CallExpression */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || + getListIfStartEndIsInListRange(node.parent.arguments, start, end); } case 232 /* VariableDeclarationList */: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); case 246 /* NamedImports */: case 250 /* NamedExports */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); + case 179 /* ObjectBindingPattern */: + case 180 /* ArrayBindingPattern */: + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); } } return undefined; @@ -97160,10 +98892,10 @@ var ts; return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { - return node.getEnd(); + return end; } - var end = node.getEnd(); var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) ? newEnd @@ -97188,7 +98920,8 @@ var ts; this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + this.newFiles = []; + this.deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map } ChangeTracker.fromContext = function (context) { @@ -97232,35 +98965,14 @@ var ts; this.deleteNode(sourceFile, node); return this; } - var id = ts.getNodeId(node); - ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); - this.deletedNodesInLists[id] = true; - if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); - if (nextToken && isSeparator(node, nextToken)) { - // find first non-whitespace position in the leading trivia of the node - var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var nextElement = containingList[index + 1]; - /// find first non-whitespace position in the leading trivia of the next node - var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node - this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - } - } - else { - var prev = containingList[index - 1]; - if (this.deletedNodesInLists[ts.getNodeId(prev)]) { - var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var end = getAdjustedEndPosition(sourceFile, node, {}); - this.deleteRange(sourceFile, { pos: pos, end: end }); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); - } - } - } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!this.deletedNodesInLists.has(node), "Deleting a node twice"); + this.deletedNodesInLists.add(node); + this.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); return this; }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { @@ -97289,10 +99001,13 @@ var ts; if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 26 /* CommaToken */ ? next : undefined; + }; ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { - return this.replaceNode(sourceFile, oldNode, newNode, { - suffix: "," + this.newLineCharacter - }); + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } @@ -97326,7 +99041,8 @@ var ts; // Otherwise, add an extra new line immediately before the error span. var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); - var text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter; + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { @@ -97399,20 +99115,38 @@ var ts; }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); - var prefix = ""; - var suffix = this.newLineCharacter; - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { - prefix = this.newLineCharacter; - // For `class C {\n}`, don't add the trailing "\n" - if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { // TODO: GH#4130 remove 'as any' - suffix = ""; - } - } var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix }); + this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { + if (cls.members.length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + // For `class C {\n}`, don't add the trailing "\n" + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + } + else { + return { prefix: "", suffix: this.newLineCharacter }; + } + } + else { + return { prefix: this.newLineCharacter, suffix: "" }; + } + }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { if (needSemicolonBetween(after, newNode)) { // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI @@ -97421,9 +99155,13 @@ var ts; } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after)); + return endPosition; }; - ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; } @@ -97468,13 +99206,16 @@ var ts; this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } }; + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); + }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, * i.e. arguments in arguments lists, parameters in parameter lists etc. * Note that separators are part of the node in statements and class elements. */ - ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { - var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); return this; @@ -97592,6 +99333,19 @@ var ts; } }); }; + ChangeTracker.prototype.finishTrailingCommaAfterDeletingNodesInList = function () { + var _this = this; + this.deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !_this.deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } + }); + }; /** * Note: after calling this, the TextChanges object must be discarded! * @param validate only for tests @@ -97600,11 +99354,24 @@ var ts; */ ChangeTracker.prototype.getChanges = function (validate) { this.finishClassesWithNodesInsertedAtStart(); - return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + this.finishTrailingCommaAfterDeletingNodesInList(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); }; return ChangeTracker; }()); textChanges_3.ChangeTracker = ChangeTracker; + // find first non-whitespace position in the leading trivia of the node + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } function getClassBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } @@ -97614,15 +99381,16 @@ var ts; return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // order changes by start position - var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); - var _loop_16 = function (i) { + // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_16(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -97631,6 +99399,11 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter) { + var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -97980,10 +99753,11 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); - function getRefactorContextLength(context) { - return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); } - ts.getRefactorContextLength = getRefactorContextLength; + ts.getRefactorContextSpan = getRefactorContextSpan; })(ts || (ts = {})); /* @internal */ var ts; @@ -98051,7 +99825,7 @@ var ts; if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { if (!decl.typeParameters) { var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); - if (typeParameters) + if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); @@ -98087,18 +99861,18 @@ var ts; } function transformJSDocType(node) { switch (node.kind) { - case 276 /* JSDocAllType */: - case 277 /* JSDocUnknownType */: + case 278 /* JSDocAllType */: + case 279 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 280 /* JSDocOptionalType */: + case 282 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 279 /* JSDocNonNullableType */: + case 281 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 278 /* JSDocNullableType */: + case 280 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: return transformJSDocFunctionType(node); case 161 /* TypeReference */: return transformJSDocTypeReference(node); @@ -98122,7 +99896,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 282 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -98403,7 +100177,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -98467,7 +100241,7 @@ var ts; case 186 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); } return false; } @@ -98540,27 +100314,30 @@ var ts; changes.deleteNode(sourceFile, assignment.parent); } else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + return true; } - changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); - return changedToDefaultExport; } } else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { convertNamedExport(sourceFile, assignment, changes, exports); } return false; - var _a; } /** * Convert `module.exports = { ... }` to individual exports.. * We can't always do this if the module has interesting members -- then it will be a default export instead. */ function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { case 155 /* GetAccessor */: case 156 /* SetAccessor */: @@ -98576,6 +100353,7 @@ var ts; ts.Debug.assertNever(prop); } }); + return statements && [statements, false]; } function convertNamedExport(sourceFile, assignment, changes, exports) { // If "originalKeywordKind" was set, this is e.g. `exports. @@ -98596,30 +100374,6 @@ var ts; convertExportsPropertyAssignment(assignment, sourceFile, changes); } } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; - switch (exported.kind) { - case 191 /* FunctionExpression */: - case 192 /* ArrowFunction */: { - // `module.exports = function f() {}` --> `export default function f() {}` - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 204 /* ClassExpression */: { - // `module.exports = class C {}` --> `export default class C {}` - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 186 /* CallExpression */: - if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) { - return convertReExportAll(exported.arguments[0], checker); - } - // falls through - default: - // `module.exports = 0;` --> `export default 0;` - return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; - } - } function convertReExportAll(reExported, checker) { // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` var moduleSpecifier = reExported.text; @@ -98695,7 +100449,7 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -98706,7 +100460,7 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } @@ -98755,7 +100509,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -98797,17 +100551,9 @@ var ts; } function makeSingleImport(localName, propertyName, moduleSpecifier) { return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); } - function makeImport(name, namedImports, moduleSpecifier) { - return makeImportDeclaration(name, namedImports, moduleSpecifier); - } - function makeImportDeclaration(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier); - } - codefix.makeImportDeclaration = makeImportDeclaration; function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); } @@ -98968,7 +100714,7 @@ var ts; var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } @@ -99014,11 +100760,11 @@ var ts; if (context.symbolToken && ts.isIdentifier(context.symbolToken)) { for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) { var declaration = existingImports_1[_i].declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); + var namespace_2 = getNamespaceImportName(declaration); + if (namespace_2) { + var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2)); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken)); } } } @@ -99085,12 +100831,6 @@ var ts; return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); } } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; - }) || false; - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -99104,274 +100844,15 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { - var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(sourceFile); + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences); return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - /** - * Looks for a existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var count = 0; - for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { - count++; - } - return count; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName); - } - } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { var fromExistingImport = ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -99390,7 +100871,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences); for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) { var info = newImportInfos_1[_i]; addNew.push(getCodeActionForNewImport(ctx, info)); @@ -99848,7 +101329,24 @@ var ts; /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + } + // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; } function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. @@ -100160,6 +101658,7 @@ var ts; ts.Diagnostics._0_is_declared_but_never_used.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -100170,9 +101669,13 @@ var ts; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start, /*deleted*/ undefined); }); + if (delDestructure.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined); }); if (deletion.length) { result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } @@ -100183,36 +101686,69 @@ var ts; return result; }, fixIds: [fixIdPrefix, fixIdDelete], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var sourceFile = context.sourceFile; - var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); - switch (context.fixId) { - case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); - } - break; - case fixIdDelete: - var importDecl = tryGetFullImport(diag.file, diag.start); - if (importDecl) { - changes.deleteNode(sourceFile, importDecl); - } - else { - tryDeleteDeclaration(changes, sourceFile, token); - } - break; - default: - ts.Debug.fail(JSON.stringify(context.fixId)); - } - }); }, + getAllCodeActions: function (context) { + // Track a set of deleted nodes that may be ancestors of other marked for deletion -- only delete the ancestors. + var deleted = new NodeSet(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var sourceFile = context.sourceFile; + var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: + // Ignore if this range was already deleted. + if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); })) + break; + var importDecl = tryGetFullImport(diag.file, diag.start); + if (importDecl) { + changes.deleteNode(sourceFile, importDecl); + } + else { + if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) { + tryDeleteDeclaration(changes, sourceFile, token, deleted); + } + } + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, }); // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(sourceFile, pos) { var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; } + function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) { + var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent)) + return false; + var decl = startToken.parent.parent; + switch (decl.kind) { + case 231 /* VariableDeclaration */: + tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors); + break; + case 148 /* Parameter */: + if (deletedAncestors) + deletedAncestors.add(decl); + changes.deleteNodeInList(sourceFile, decl); + break; + case 181 /* BindingElement */: + if (deletedAncestors) + deletedAncestors.add(decl); + changes.deleteNode(sourceFile, decl); + break; + default: + return ts.Debug.assertNever(decl); + } + return true; + } function getToken(sourceFile, pos) { - var token = ts.findPrecedingToken(pos, sourceFile); + var token = ts.findPrecedingToken(pos, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); // this handles var ["computed"] = 12; return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token; } @@ -100237,38 +101773,45 @@ var ts; } return false; } - function tryDeleteDeclaration(changes, sourceFile, token) { + function tryDeleteDeclaration(changes, sourceFile, token, deletedAncestors) { switch (token.kind) { case 71 /* Identifier */: - tryDeleteIdentifier(changes, sourceFile, token); + tryDeleteIdentifier(changes, sourceFile, token, deletedAncestors); break; case 151 /* PropertyDeclaration */: case 245 /* NamespaceImport */: + if (deletedAncestors) + deletedAncestors.add(token.parent); changes.deleteNode(sourceFile, token.parent); break; default: - tryDeleteDefault(changes, sourceFile, token); + tryDeleteDefault(changes, sourceFile, token, deletedAncestors); } } - function tryDeleteDefault(changes, sourceFile, token) { + function tryDeleteDefault(changes, sourceFile, token, deletedAncestors) { if (ts.isDeclarationName(token)) { + if (deletedAncestors) + deletedAncestors.add(token.parent); changes.deleteNode(sourceFile, token.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + if (deletedAncestors) + deletedAncestors.add(token.parent.parent); changes.deleteNode(sourceFile, token.parent.parent); } } - function tryDeleteIdentifier(changes, sourceFile, identifier) { + function tryDeleteIdentifier(changes, sourceFile, identifier, deletedAncestors) { var parent = identifier.parent; switch (parent.kind) { case 231 /* VariableDeclaration */: - tryDeleteVariableDeclaration(changes, sourceFile, parent); + tryDeleteVariableDeclaration(changes, sourceFile, parent, deletedAncestors); break; case 147 /* TypeParameter */: - var typeParameters = parent.parent.typeParameters; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(parent.parent); if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; + var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, end, /*includeJsDocComment*/ false); ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); changes.deleteNodeRange(sourceFile, previousToken, nextToken); @@ -100299,6 +101842,20 @@ var ts; changes.deleteNodeInList(sourceFile, parent); } break; + case 181 /* BindingElement */: { + var pattern = parent.parent; + switch (pattern.kind) { + case 180 /* ArrayBindingPattern */: + changes.deleteNode(sourceFile, parent); // Don't delete ',' + break; + case 179 /* ObjectBindingPattern */: + changes.deleteNodeInList(sourceFile, parent); + break; + default: + return ts.Debug.assertNever(pattern); + } + break; + } // handle case where 'import a = A;' case 242 /* ImportEqualsDeclaration */: var importEquals = ts.getAncestor(identifier, 242 /* ImportEqualsDeclaration */); @@ -100337,7 +101894,7 @@ var ts; tryDeleteNamedImportBinding(changes, sourceFile, parent); break; default: - tryDeleteDefault(changes, sourceFile, identifier); + tryDeleteDefault(changes, sourceFile, identifier, deletedAncestors); break; } } @@ -100360,15 +101917,19 @@ var ts; } } // token.parent is a variableDeclaration - function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { + function tryDeleteVariableDeclaration(changes, sourceFile, varDecl, deletedAncestors) { switch (varDecl.parent.parent.kind) { case 219 /* ForStatement */: { var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; if (forInitializer.declarations.length === 1) { + if (deletedAncestors) + deletedAncestors.add(forInitializer); changes.deleteNode(sourceFile, forInitializer); } else { + if (deletedAncestors) + deletedAncestors.add(varDecl); changes.deleteNodeInList(sourceFile, varDecl); } break; @@ -100377,6 +101938,8 @@ var ts; var forOfStatement = varDecl.parent.parent; ts.Debug.assert(forOfStatement.initializer.kind === 232 /* VariableDeclarationList */); var forOfInitializer = forOfStatement.initializer; + if (deletedAncestors) + deletedAncestors.add(forOfInitializer.declarations[0]); changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); break; case 220 /* ForInStatement */: @@ -100385,13 +101948,131 @@ var ts; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { + if (deletedAncestors) + deletedAncestors.add(variableStatement); changes.deleteNode(sourceFile, variableStatement); } else { + if (deletedAncestors) + deletedAncestors.add(varDecl); changes.deleteNodeInList(sourceFile, varDecl); } } } + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + switch (container.kind) { + case 216 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + break; + } + // falls through + case 218 /* WhileStatement */: + case 219 /* ForStatement */: + changes.deleteNode(sourceFile, container); + break; + default: + if (ts.isBlock(statement.parent)) { + split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); + } + else { + changes.deleteNode(sourceFile, statement); + } + } + } + function shouldRemove(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 235 /* InterfaceDeclaration */: + case 236 /* TypeAliasDeclaration */: + return true; + case 238 /* ModuleDeclaration */: + return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; + case 237 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + } + } + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + ts.Debug.assert(index !== -1); + return arr.slice(index); + } + // Calls 'cb' with the start and end of each range where 'pred' is true. + function split(arr, pred, cb) { + ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -100413,7 +102094,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 278 /* JSDocNullableType */) { + if (typeNode.kind === 280 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -100433,7 +102114,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 278 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; + var fixedType = typeNode.kind === 280 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -100811,16 +102492,16 @@ var ts; } var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var seenFunctions = ts.createMap(); + var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, markSeen); }); }, }); @@ -100834,7 +102515,7 @@ var ts; return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { return undefined; } @@ -100843,17 +102524,18 @@ var ts; // Variable and Property declarations case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) { + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); return symbol.valueDeclaration; } + return undefined; } } var containingFunction = ts.getContainingFunction(token); @@ -100869,7 +102551,7 @@ var ts; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { + if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); return param; @@ -101061,6 +102743,16 @@ var ts; case 185 /* ElementAccessExpression */: inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); break; + case 231 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through default: return inferTypeFromContextualType(node, checker, usageContext); } @@ -101232,7 +102924,7 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); + return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); @@ -101349,7 +103041,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -101506,6 +103198,290 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +// Used by importFixes to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + // For each symlink/original for a module, returns a list of ways to import that file. + function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var compilerOptions = program.getCompilerOptions(); + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName); + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + // For a type definition, we can strip `/index` even with classic resolution. + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -101575,7 +103551,40 @@ var ts; } } function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + ts.Debug.assert(token.kind === 91 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 178 /* ImportType */); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + changes.replaceNode(sourceFile, importType, newTypeNode); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -101593,7 +103602,7 @@ var ts; * Exported for tests. */ function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -101662,7 +103671,7 @@ var ts; extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); if (parsedFunctionIndexMatch) { @@ -102774,8 +104783,8 @@ var ts; i_1++; } // Note that we add the current node's type parameters *after* updating the corresponding scope. - if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { - for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { var typeParameterDecl = _b[_a]; var typeParameter = checker.getTypeAtLocation(typeParameterDecl); if (allTypeParameterUsages.has(typeParameter.id.toString())) { @@ -102797,7 +104806,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_17 = function (i) { + var _loop_19 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -102837,21 +104846,11 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_17(i); + _loop_19(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; - function hasTypeParameters(node) { - return ts.isDeclarationWithTypeParameters(node) && - node.typeParameters !== undefined && - node.typeParameters.length > 0; - } function isInGenericContext(node) { - for (; node; node = node.parent) { - if (hasTypeParameters(node)) { - return true; - } - } - return false; + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); } function recordTypeParameterUsages(type) { // PERF: This is potentially very expensive. `type` could be a library type with @@ -103116,8 +105115,8 @@ var ts; var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition; - if (!getConvertibleFieldAtPosition(file, startPosition)) + var file = context.file; + if (!getConvertibleFieldAtPosition(context, file)) return undefined; return [{ name: actionName, @@ -103131,27 +105130,46 @@ var ts; }]; } function getEditsForAction(context, _actionName) { - var file = context.file, startPosition = context.startPosition; - var fieldInfo = getConvertibleFieldAtPosition(file, startPosition); + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context, file); if (!fieldInfo) return undefined; var isJS = ts.isSourceFileJavaScript(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration; + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); var isInClassLike = ts.isClassLike(container); + // avoid Readonly modifier because it will convert to get accessor + var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; var accessorModifiers = isInClassLike - ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 /* Private */ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) : declaration.modifiers + ? !modifierFlags || modifierFlags & 8 /* Private */ + ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined; var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined; - updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container); + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); - var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); insertAccessor(changeTracker, file, getAccessor, declaration, container); - insertAccessor(changeTracker, file, setAccessor, declaration, container); + if (isReadonly) { + // readonly modifier only existed in classLikeDeclaration + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } var edits = changeTracker.getChanges(); var renameFilename = file.fileName; - var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1; - var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false); + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function isConvertableName(name) { @@ -103171,24 +105189,32 @@ var ts; var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined); return modifiers && ts.createNodeArray(modifiers); } - function getConvertibleFieldAtPosition(file, startPosition) { + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + function getConvertibleFieldAtPosition(context, file) { + var startPosition = context.startPosition, endPosition = context.endPosition; var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); - // make sure propertyDeclaration have AccessibilityModifier or Static Modifier - var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */; - if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier + var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) + || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; - var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name); - var accessorName = createPropertyName(declaration.name.text, declaration.name); - ts.suppressLeadingAndTrailingTrivia(fieldName); - ts.suppressLeadingAndTrailingTrivia(declaration); + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file.text), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file.text) : name, declaration.name); return { isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), container: declaration.kind === 148 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name, declaration: declaration, fieldName: fieldName, accessorName: accessorName, + renameAccessor: startWithUnderscore }; } function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { @@ -103212,16 +105238,11 @@ var ts; var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } - function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) { - var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer); - changeTracker.insertNodeAtClassStart(file, classLikeContainer, property); - changeTracker.deleteNodeInList(file, declaration); - } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); changeTracker.replacePropertyAssignment(file, declaration, assignment); } - function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) { + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { if (ts.isPropertyDeclaration(declaration)) { updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); } @@ -103229,19 +105250,636 @@ var ts; updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container); + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { ts.isParameterPropertyDeclaration(declaration) ? changeTracker.insertNodeAtClassStart(file, container, accessor) - : changeTracker.insertNodeAfter(file, declaration, accessor); + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + if (!constructor.body) + return; + var file = context.file, program = context.program, cancellationToken = context.cancellationToken; + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); }); + ts.forEach(referenceEntries, function (entry) { + var parent = entry.parent; + var accessorName = ts.createIdentifier(fieldName.text); + var node = ts.isBinaryExpression(parent) + ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) + : ts.isPropertyAccessExpression(parent) + ? ts.updatePropertyAccess(parent, parent.expression, accessorName) + : ts.Debug.fail("Unexpected write access token"); + changeTracker.replaceNode(file, parent, node); + }); } })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + return undefined; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getFirstAndLastStatementToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + // Can't only partially include the start node or be partially into the next node + if (range.pos > statements[startNodeIndex].getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + // Can't be partially into the next node + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + } + function doChange(oldFile, program, toMove, changes, host) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + // If previous file was global, this is easy. + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. + function getStatementsToMove(context) { + var statements = context.file.statements; + var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var all = []; + var ranges = []; + var rangeToMove = statements.slice(first, afterLast); + ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { + for (var i = start; i < afterEnd; i++) + all.push(rangeToMove[i]); + ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); + }); + return { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 243 /* ImportDeclaration */: + return true; + case 242 /* ImportEqualsDeclaration */: + return !ts.hasModifier(node, 1 /* Export */); + case 213 /* VariableStatement */: + return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + if (importsFromNewFile) { + changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last; + changes.deleteNodeRange(sourceFile, first_1, last_3); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_20 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_21 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_21(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_20(sourceFile); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 243 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 242 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path); + } + else { + ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. + var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2 /* Const */; } + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 243 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 242 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.deleteNode(sourceFile, importDecl); + } + break; + case 231 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 245 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.deleteNode(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.deleteNode(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.deleteNode(sourceFile, namedBindings); + } + else if (namedBindings.kind === 246 /* NamedImports */) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.deleteNodeInList(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 71 /* Identifier */: + if (isUnused(name)) { + changes.deleteNode(sourceFile, name); + } + break; + case 180 /* ArrayBindingPattern */: + break; + case 179 /* ObjectBindingPattern */: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.deleteNode(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.deleteNode(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512 /* Default */)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + // Below should all be utilities + function isInImport(decl) { + switch (decl.kind) { + case 242 /* ImportEqualsDeclaration */: + case 247 /* ImportSpecifier */: + case 244 /* ImportClause */: + return true; + case 231 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 181 /* BindingElement */: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 243 /* ImportDeclaration */: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 242 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : undefined; + case 231 /* VariableDeclaration */: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 245 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 71 /* Identifier */: + return keep(name) ? name : undefined; + case 180 /* ArrayBindingPattern */: + return name; + case 179 /* ObjectBindingPattern */: { + // We can't handle nested destructurings or property names well here, so just copy them all. + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = /** @class */ (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 233 /* FunctionDeclaration */: + case 234 /* ClassDeclaration */: + case 238 /* ModuleDeclaration */: + case 237 /* EnumDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 242 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 233 /* FunctionDeclaration */: + case 234 /* ClassDeclaration */: + case 238 /* ModuleDeclaration */: + case 237 /* EnumDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 242 /* ImportEqualsDeclaration */: + return cb(statement); + case 213 /* VariableStatement */: + return ts.forEach(statement.declarationList.declarations, cb); + case 215 /* ExpressionStatement */: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + ? cb(statement) + : undefined; + } + } + } + function nameOfTopLevelDeclaration(d) { + return d.kind === 215 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + return ts.isVariableDeclaration(d) ? d.parent.parent : d; + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); + switch (d.kind) { + case 233 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 234 /* ClassDeclaration */: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 213 /* VariableStatement */: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 238 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 237 /* EnumDeclaration */: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 236 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 235 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 242 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 215 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 233 /* FunctionDeclaration */: + case 234 /* ClassDeclaration */: + return [decl.name.text]; + case 213 /* VariableStatement */: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 238 /* ModuleDeclaration */: + case 237 /* EnumDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 242 /* ImportEqualsDeclaration */: + return undefined; + case 215 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + ts.Debug.assertNever(decl); + } + } + /** Creates `exports.x = x;` */ + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var sourcemaps; (function (sourcemaps) { @@ -103563,7 +106201,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 275 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 277 /* FirstJSDocNode */ || kid.kind > 297 /* LastJSDocNode */; }); return child.kind < 145 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -103633,7 +106271,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(298 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -104156,6 +106794,9 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -104185,9 +106826,18 @@ var ts; return ts.isString(info) ? undefined : info; }; HostCache.prototype.getRootFileNames = function () { - return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { - return ts.isString(entry) ? entry : entry.hostFileName; + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6 /* JSON */) { + names.push(entry.hostFileName); + } + } }); + return names; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); @@ -104363,6 +107013,7 @@ var ts; } ts.createSourceFileLikeCache = createSourceFileLikeCache; function createLanguageService(host, documentRegistry, syntaxOnly) { + var _a; if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } if (syntaxOnly === void 0) { syntaxOnly = false; } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -104466,7 +107117,14 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: hostCache.getProjectReferences() + }; + program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; @@ -104670,6 +107328,11 @@ var ts; } return checker.getSymbolAtLocation(node); } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); + return file.getLineAndCharacterOfPosition(position); + } // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/gm; var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; @@ -104741,27 +107404,28 @@ var ts; } function makeGetTargetOfMappedPosition(extract, create) { return getTargetOfMappedPosition; - function getTargetOfMappedPosition(input) { + function getTargetOfMappedPosition(input, original) { + if (original === void 0) { original = input; } var info = extract(input); if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { - var file = program.getSourceFile(info.fileName); - if (!file) { + var file_18 = program.getSourceFile(info.fileName); + if (!file_18) { var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); - file = sourcemappedFileCache.get(path); + file_18 = sourcemappedFileCache.get(path); } - if (!file) { + if (!file_18) { return input; } - var mapper = getSourceMapper(info.fileName, file); + var mapper = getSourceMapper(info.fileName, file_18); var newLoc = mapper.getOriginalPosition(info); if (newLoc === info) return input; - return getTargetOfMappedPosition(create(newLoc, input)); + return getTargetOfMappedPosition(create(newLoc, input, original), original); } return input; } } - var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({ containerKind: info.containerKind, containerName: info.containerName, fileName: newLoc.fileName, @@ -104770,10 +107434,12 @@ var ts; textSpan: { start: newLoc.position, length: info.textSpan.length - } + }, + originalFileName: original.fileName, + originalTextSpan: original.textSpan }); }); function getTargetOfMappedDeclarationFiles(infos) { - return ts.map(infos, getTargetOfMappedDeclarationInfo); + return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); }); } /// Goto definition function getDefinitionAtPosition(fileName, position) { @@ -104806,10 +107472,12 @@ var ts; textSpan: { start: newLoc.position, length: info.textSpan.length - } + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan }); }); function getTargetOfMappedImplementationLocations(infos) { - return ts.map(infos, getTargetOfMappedImplementationLocation); + return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); }); } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); @@ -105317,8 +107985,8 @@ var ts; getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: toLineColumnOffset }; - var _a; } ts.createLanguageService = createLanguageService; /* @internal */ @@ -105389,20 +108057,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_6 = []; + var result_7 = []; var symbol = type.getProperty(name); if (type.flags & 131072 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_7.push(symbol); } }); - return result_6; + return result_7; } if (symbol) { - result_6.push(symbol); - return result_6; + result_7.push(symbol); + return result_7; } } return undefined; @@ -105469,7 +108137,7 @@ var ts; return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { - return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { @@ -105484,7 +108152,7 @@ var ts; return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } function spanInNextNode(node) { - return spanInNode(ts.findNextToken(node, node.parent)); + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); } function spanInNode(node) { if (node) { @@ -106823,5 +109491,3 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = ts.versionMajorMinor; - -//# sourceMappingURL=typescriptServices.js.map diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 6c81f213986..d237cc98eee 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -337,32 +337,36 @@ declare namespace ts { EnumMember = 272, SourceFile = 273, Bundle = 274, - JSDocTypeExpression = 275, - JSDocAllType = 276, - JSDocUnknownType = 277, - JSDocNullableType = 278, - JSDocNonNullableType = 279, - JSDocOptionalType = 280, - JSDocFunctionType = 281, - JSDocVariadicType = 282, - JSDocComment = 283, - JSDocTypeLiteral = 284, - JSDocTag = 285, - JSDocAugmentsTag = 286, - JSDocClassTag = 287, - JSDocParameterTag = 288, - JSDocReturnTag = 289, - JSDocTypeTag = 290, - JSDocTemplateTag = 291, - JSDocTypedefTag = 292, - JSDocPropertyTag = 293, - SyntaxList = 294, - NotEmittedStatement = 295, - PartiallyEmittedExpression = 296, - CommaListExpression = 297, - MergeDeclarationMarker = 298, - EndOfDeclarationMarker = 299, - Count = 300, + UnparsedSource = 275, + InputFiles = 276, + JSDocTypeExpression = 277, + JSDocAllType = 278, + JSDocUnknownType = 279, + JSDocNullableType = 280, + JSDocNonNullableType = 281, + JSDocOptionalType = 282, + JSDocFunctionType = 283, + JSDocVariadicType = 284, + JSDocComment = 285, + JSDocTypeLiteral = 286, + JSDocSignature = 287, + JSDocTag = 288, + JSDocAugmentsTag = 289, + JSDocClassTag = 290, + JSDocCallbackTag = 291, + JSDocParameterTag = 292, + JSDocReturnTag = 293, + JSDocTypeTag = 294, + JSDocTemplateTag = 295, + JSDocTypedefTag = 296, + JSDocPropertyTag = 297, + SyntaxList = 298, + NotEmittedStatement = 299, + PartiallyEmittedExpression = 300, + CommaListExpression = 301, + MergeDeclarationMarker = 302, + EndOfDeclarationMarker = 303, + Count = 304, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -388,10 +392,10 @@ declare namespace ts { FirstBinaryOperator = 27, LastBinaryOperator = 70, FirstNode = 145, - FirstJSDocNode = 275, - LastJSDocNode = 293, - FirstJSDocTagNode = 285, - LastJSDocTagNode = 293 + FirstJSDocNode = 277, + LastJSDocNode = 297, + FirstJSDocTagNode = 288, + LastJSDocTagNode = 297 } enum NodeFlags { None = 0, @@ -415,6 +419,7 @@ declare namespace ts { ThisNodeOrAnySubNodesHasError = 131072, HasAggregatedChildData = 262144, JSDoc = 2097152, + JsonFile = 16777216, BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, @@ -1149,7 +1154,7 @@ declare namespace ts { kind: SyntaxKind.NotEmittedStatement; } /** - * A list of comma-seperated expressions. This node is only created by transformations. + * A list of comma-separated expressions. This node is only created by transformations. */ interface CommaListExpression extends Expression { kind: SyntaxKind.CommaListExpression; @@ -1277,7 +1282,7 @@ declare namespace ts { block: Block; } type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; + type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; @@ -1534,6 +1539,19 @@ declare namespace ts { name?: Identifier; typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; } + interface JSDocCallbackTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocCallbackTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression: JSDocSignature; + } + interface JSDocSignature extends JSDocType, Declaration { + kind: SyntaxKind.JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + type: JSDocReturnTag | undefined; + } interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; @@ -1644,12 +1662,32 @@ declare namespace ts { } interface Bundle extends Node { kind: SyntaxKind.Bundle; + prepends: ReadonlyArray; sourceFiles: ReadonlyArray; } + interface InputFiles extends Node { + kind: SyntaxKind.InputFiles; + javascriptText: string; + declarationText: string; + } + interface UnparsedSource extends Node { + kind: SyntaxKind.UnparsedSource; + text: string; + } interface JsonSourceFile extends SourceFile { - jsonObject?: ObjectLiteralExpression; + statements: NodeArray; + } + interface TsConfigSourceFile extends JsonSourceFile { extendedSourceFiles?: string[]; } + interface JsonMinusNumericLiteral extends PrefixUnaryExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: SyntaxKind.MinusToken; + operand: NumericLiteral; + } + interface JsonObjectExpressionStatement extends ExpressionStatement { + expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral; + } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; getSourceFile(fileName: string): SourceFile | undefined; @@ -1705,12 +1743,19 @@ declare namespace ts { */ getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; + getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + } + interface ResolvedProjectReference { + commandLine: ParsedCommandLine; + sourceFile: SourceFile; } interface CustomTransformers { - /** Custom transformers to evaluate before built-in transformations. */ + /** Custom transformers to evaluate before built-in .js transformations. */ before?: TransformerFactory[]; - /** Custom transformers to evaluate after built-in transformations. */ + /** Custom transformers to evaluate after built-in .js transformations. */ after?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .d.ts transformations. */ + afterDeclarations?: TransformerFactory[]; } interface SourceMapSpan { /** Line number in the .js file. */ @@ -1853,7 +1898,9 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + GenerateNamesForShadowedTypeParams = 4, UseStructuralFallback = 8, + ForbidIndexedAccessSymbolReferences = 16, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, UseOnlyExternalAliasing = 128, @@ -2217,6 +2264,7 @@ declare namespace ts { objectType: Type; indexType: Type; constraint?: Type; + simplified?: Type; } type TypeVariable = TypeParameter | IndexedAccessType; interface IndexType extends InstantiableType { @@ -2251,7 +2299,7 @@ declare namespace ts { Construct = 1 } interface Signature { - declaration?: SignatureDeclaration; + declaration?: SignatureDeclaration | JSDocSignature; typeParameters?: TypeParameter[]; parameters: Symbol[]; } @@ -2274,7 +2322,9 @@ declare namespace ts { AlwaysStrict = 64, PriorityImpliesCombination = 28 } - interface JsFileExtensionInfo { + /** @deprecated Use FileExtensionInfo instead. */ + type JsFileExtensionInfo = FileExtensionInfo; + interface FileExtensionInfo { extension: string; isMixedContent: boolean; scriptKind?: ScriptKind; @@ -2322,7 +2372,17 @@ declare namespace ts { interface PluginImport { name: string; } - type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined; + interface ProjectReference { + /** A normalized path on disk */ + path: string; + /** The path as the user originally wrote it */ + originalPath?: string; + /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ + prepend?: boolean; + /** True if it is intended that this reference form a circularity */ + circular?: boolean; + } + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -2378,6 +2438,7 @@ declare namespace ts { project?: string; reactNamespace?: string; jsxFactory?: string; + composite?: boolean; removeComments?: boolean; rootDir?: string; rootDirs?: string[]; @@ -2393,11 +2454,12 @@ declare namespace ts { suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; traceResolution?: boolean; + resolveJsonModule?: boolean; types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; esModuleInterop?: boolean; - [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; + [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; } interface TypeAcquisition { enableAutoDiscovery?: boolean; @@ -2437,7 +2499,12 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, - JSON = 6 + JSON = 6, + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + Deferred = 7 } enum ScriptTarget { ES3 = 0, @@ -2447,6 +2514,7 @@ declare namespace ts { ES2017 = 4, ES2018 = 5, ESNext = 6, + JSON = 100, Latest = 6 } enum LanguageVariant { @@ -2458,6 +2526,7 @@ declare namespace ts { options: CompilerOptions; typeAcquisition?: TypeAcquisition; fileNames: string[]; + projectReferences?: ReadonlyArray; raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; @@ -2469,8 +2538,17 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; + projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } + interface CreateProgramOptions { + rootNames: ReadonlyArray; + options: CompilerOptions; + projectReferences?: ReadonlyArray; + host?: CompilerHost; + oldProgram?: Program; + configFileParsingDiagnostics?: ReadonlyArray; + } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2561,6 +2639,7 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; + readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files @@ -2918,10 +2997,11 @@ declare namespace ts { readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** - * This should be cryptographically secure. * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) */ createHash?(data: string): string; + /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */ + createSHA256Hash?(data: string): string; getMemoryUsage?(): number; exit(exitCode?: number): void; realpath?(path: string): string; @@ -3298,6 +3378,8 @@ declare namespace ts { function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; + function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag; + function isJSDocSignature(node: Node): node is JSDocSignature; } declare namespace ts { /** @@ -3423,6 +3505,8 @@ declare namespace ts { function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; + function createStringLiteral(text: string): StringLiteral; + function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ @@ -3727,8 +3811,10 @@ declare namespace ts { function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; function createCommaList(elements: ReadonlyArray): CommaListExpression; function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; - function createBundle(sourceFiles: ReadonlyArray): Bundle; - function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle; + function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createUnparsedSourceFile(text: string): UnparsedSource; + function createInputFiles(javascript: string, declaration: string): InputFiles; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression; function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression; @@ -3792,6 +3878,7 @@ declare namespace ts { function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function moveSyntheticComments(node: T, original: Node): T; /** * Gets the constant value to emit for an expression. */ @@ -3935,6 +4022,7 @@ declare namespace ts { * @param configFileParsingDiagnostics - error during config file parsing * @returns A 'Program' object. */ + function createProgram(createProgramOptions: CreateProgramOptions): Program; function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; } declare namespace ts { @@ -4074,7 +4162,6 @@ declare namespace ts { function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; } declare namespace ts { - type DiagnosticReporter = (diagnostic: Diagnostic) => void; type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; @@ -4137,15 +4224,6 @@ declare namespace ts { /** Compiler options */ options: CompilerOptions; } - /** - * Reports config file diagnostics - */ - interface ConfigFileDiagnosticsReporter { - /** - * Reports unrecoverable error when parsing config file - */ - onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; - } /** * Host to create watch with config file */ @@ -4192,6 +4270,26 @@ declare namespace ts { } declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors + */ + interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter { + getCurrentDirectory(): string; + } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4213,7 +4311,7 @@ declare namespace ts { * Read tsconfig.json file * @param fileName The path to the config file */ - function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile; + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile; /** * Convert the json syntax tree into the json value */ @@ -4225,7 +4323,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; /** * Parse the contents of a config file (tsconfig.json). * @param jsonNode The contents of the config file to parse @@ -4233,7 +4331,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -4252,7 +4350,7 @@ declare namespace ts { getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; getFullStart(): number; getEnd(): number; - getWidth(sourceFile?: SourceFile): number; + getWidth(sourceFile?: SourceFileLike): number; getFullWidth(): number; getLeadingTriviaWidth(sourceFile?: SourceFile): number; getFullText(sourceFile?: SourceFile): string; @@ -4364,6 +4462,7 @@ declare namespace ts { getScriptKind?(fileName: string): ScriptKind; getScriptVersion(fileName: string): string; getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; + getProjectReferences?(): ReadonlyArray | undefined; getLocalizedDiagnosticMessages?(): any; getCancellationToken?(): HostCancellationToken; getCurrentDirectory(): string; @@ -4378,6 +4477,7 @@ declare namespace ts { fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getDirectories?(directoryName: string): string[]; /** @@ -4393,6 +4493,7 @@ declare namespace ts { readonly includeCompletionsForModuleExports?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly allowTextChangesInNewFiles?: boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -4441,6 +4542,7 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; + toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; @@ -4465,9 +4567,10 @@ declare namespace ts { fileName: string; } type OrganizeImportsScope = CombinedCodeFixScope; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; interface GetCompletionsAtPositionOptions extends UserPreferences { /** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */ - triggerCharacter?: string; + triggerCharacter?: CompletionsTriggerCharacter; /** @deprecated Use includeCompletionsForModuleExports */ includeExternalModuleExports?: boolean; /** @deprecated Use includeCompletionsWithInsertText */ @@ -4534,6 +4637,7 @@ declare namespace ts { interface FileTextChanges { fileName: string; textChanges: TextChange[]; + isNewFile?: boolean; } interface CodeAction { /** Description of the code action to display in the UI of the editor */ @@ -4620,6 +4724,12 @@ declare namespace ts { interface DocumentSpan { textSpan: TextSpan; fileName: string; + /** + * If the span represents a location that was remapped (e.g. via a .d.ts.map file), + * then the original filename and span will be specified here + */ + originalTextSpan?: TextSpan; + originalFileName?: string; } interface RenameLocation extends DocumentSpan { } @@ -4717,9 +4827,7 @@ declare namespace ts { insertSpaceBeforeTypeAnnotation?: boolean; indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } - interface DefinitionInfo { - fileName: string; - textSpan: TextSpan; + interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; containerKind: ScriptElementKind; @@ -4865,6 +4973,20 @@ declare namespace ts { * the 'Collapse to Definitions' command is invoked. */ autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + enum OutliningSpanKind { + /** Single or multi-line comments */ + Comment = "comment", + /** Sections marked by '// #region' and '// #endregion' comments */ + Region = "region", + /** Declarations and expressions */ + Code = "code", + /** Contiguous blocks of import declarations */ + Imports = "imports" } enum OutputFileType { JavaScript = 0, @@ -4988,7 +5110,9 @@ declare namespace ts { /** * */ - jsxAttribute = "JSX attribute" + jsxAttribute = "JSX attribute", + /** String literal */ + string = "string" } enum ScriptElementKindModifier { none = "", diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 86c2e32ef0e..5a20323ef59 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -350,38 +350,42 @@ var ts; // Top-level nodes SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile"; SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 275] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 276] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 277] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 278] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 279] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 280] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 281] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 282] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 283] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 284] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 285] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 286] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 287] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 288] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 289] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 290] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 291] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 292] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 293] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 294] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 295] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 296] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 297] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 298] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 299] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 300] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 301] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 302] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 303] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 304] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -408,10 +412,10 @@ var ts; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 277] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 297] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 288] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 297] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -451,6 +455,7 @@ var ts; NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; @@ -513,10 +518,9 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; // Flags - GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; @@ -591,9 +595,9 @@ var ts; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; @@ -885,6 +889,8 @@ var ts; TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType"; TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive"; /* @internal */ + TypeFlags[TypeFlags["UnionOfUnitTypes"] = 268435456] = "UnionOfUnitTypes"; + /* @internal */ TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; @@ -920,6 +926,8 @@ var ts; TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit"; /* @internal */ + TypeFlags[TypeFlags["NotUnit"] = 8374815] = "NotUnit"; + /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening"; /* @internal */ TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags"; @@ -1072,6 +1080,11 @@ var ts; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -1082,6 +1095,7 @@ var ts; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; @@ -1894,8 +1908,8 @@ var ts; } ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ - function findIndex(array, predicate) { - for (var i = 0; i < array.length; i++) { + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -1903,6 +1917,15 @@ var ts; return -1; } ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; /** * Returns the first truthy result of `callback`, or else fails. * This is like `forEach`, but never returns undefined. @@ -2255,6 +2278,24 @@ var ts; return false; } ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; function concatenate(array1, array2) { if (!some(array2)) return array1; @@ -2498,6 +2539,23 @@ var ts; return to; } ts.addRange = addRange; + /** + * Appends a range of value to begin of an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + function prependRange(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + to.unshift.apply(to, from); + return to; + } + ts.prependRange = prependRange; /** * @return Whether the value was added. */ @@ -2747,17 +2805,18 @@ var ts; } ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { + var _a; var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { result.push(map ? map(value) : value); } return result; - var _b; } ts.arrayFrom = arrayFrom; function forEachEntry(map, callback) { + var _a; var iterator = map.entries(); - for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { var key = pair[0], value = pair[1]; var result = callback(value, key); if (result) { @@ -2765,19 +2824,18 @@ var ts; } } return undefined; - var _b; } ts.forEachEntry = forEachEntry; function forEachKey(map, callback) { + var _a; var iterator = map.keys(); - for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { var result = callback(key); if (result) { return result; } } return undefined; - var _b; } ts.forEachKey = forEachKey; function copyEntries(source, target) { @@ -3334,11 +3392,11 @@ var ts; comparer(a[key], b[key]); } ts.compareProperties = compareProperties; - function getDiagnosticFileName(diagnostic) { - return diagnostic.file ? diagnostic.file.fileName : undefined; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; } function compareDiagnostics(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -3370,106 +3428,6 @@ var ts; // We still have one chain remaining. The shorter chain should come first. return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; } - function normalizeSlashes(path) { - return path.replace(/\\/g, "/"); - } - ts.normalizeSlashes = normalizeSlashes; - /** - * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") - */ - function getRootLength(path) { - if (path.charCodeAt(0) === 47 /* slash */) { - if (path.charCodeAt(1) !== 47 /* slash */) - return 1; - var p1 = path.indexOf("/", 2); - if (p1 < 0) - return 2; - var p2 = path.indexOf("/", p1 + 1); - if (p2 < 0) - return p1 + 1; - return p2 + 1; - } - if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) - return 3; - } - // Per RFC 1738 'file' URI schema has the shape file:/// - // if is omitted then it is assumed that host value is 'localhost', - // however slash after the omitted is not removed. - // file:///folder1/file1 - this is a correct URI - // file://folder2/file2 - this is an incorrect URI - if (path.lastIndexOf("file:///", 0) === 0) { - return "file:///".length; - } - var idx = path.indexOf("://"); - if (idx !== -1) { - return idx + "://".length; - } - return 0; - } - ts.getRootLength = getRootLength; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var directorySeparatorCharCode = 47 /* slash */; - function getNormalizedParts(normalizedSlashedPath, rootLength) { - var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); - var normalized = []; - for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { - var part = parts_1[_i]; - if (part !== ".") { - if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { - normalized.pop(); - } - else { - // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, - // e.g. "path//file.ts". Drop these before re-joining the parts. - if (part) { - normalized.push(part); - } - } - } - } - return normalized; - } - function normalizePath(path) { - return normalizePathAndParts(path).path; - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - var root = path.substr(0, rootLength); - var parts = getNormalizedParts(path, rootLength); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - /** A path ending with '/' refers to a directory only, never a file. */ - function pathEndsWithDirectorySeparator(path) { - return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; - } - ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; - function getDirectoryPath(path) { - return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function isUrl(path) { - return path && !isRootedDiskPath(path) && stringContains(path, "://"); - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0 /* ES3 */; } @@ -3501,6 +3459,10 @@ var ts; : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; } @@ -3521,202 +3483,455 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + // + // Paths + // + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ function isRootedDiskPath(path) { - return path && getRootLength(path) !== 0; + return getEncodedRootLength(path) > 0; } ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); } ts.convertToRelativePath = convertToRelativePath; - function normalizedPathComponents(path, rootLength) { - var normalizedParts = getNormalizedParts(path, rootLength); - return [path.substr(0, rootLength)].concat(normalizedParts); + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); } - function getNormalizedPathComponents(path, currentDirectory) { - path = normalizeSlashes(path); + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); var rootLength = getRootLength(path); - if (rootLength === 0) { - // If the path is not rooted it is relative to current directory - path = combinePaths(normalizeSlashes(currentDirectory), path); - rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); } - return normalizedPathComponents(path, rootLength); + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); } ts.getNormalizedPathComponents = getNormalizedPathComponents; function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); } ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getNormalizedPathFromPathComponents(pathComponents) { - if (pathComponents && pathComponents.length) { - return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); - } + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + if (pathComponents.length === 1) + return root; + return root + pathComponents.slice(1).join(ts.directorySeparator); } - ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; - function getNormalizedPathComponentsOfUrl(url) { - // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ - // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] - var urlLength = url.length; - // Initial root length is http:// part - var rootLength = url.indexOf("://") + "://".length; - while (rootLength < urlLength) { - // Consume all immediate slashes in the protocol - // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// - if (url.charCodeAt(rootLength) === 47 /* slash */) { - rootLength++; - } - else { - // non slash character means we continue proceeding to next component of root search + ts.getPathFromPathComponents = getPathFromPathComponents; + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) break; - } } - // there are no parts after http:// just return current string as the pathComponent - if (rootLength === urlLength) { - return [url]; + if (start === 0) { + return toComponents; } - // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) - var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); - if (indexOfNextSlash !== -1) { - // Found the "/" after the website.com so the root is length of http://www.website.com/ - // and get components after the root normally like any other folder components - rootLength = indexOfNextSlash + 1; - return normalizedPathComponents(url, rootLength); - } - else { - // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" - // eg. if url passed in was http://website.com we want to use root as [http://website.com/] - // so that other path manipulations will be correct and it can be merged with relative paths correctly - return [url + ts.directorySeparator]; + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); } + return [""].concat(relative, components); } - function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { - if (isUrl(pathOrUrl)) { - return getNormalizedPathComponentsOfUrl(pathOrUrl); - } - else { - return getNormalizedPathComponents(pathOrUrl, currentDirectory); - } + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] - directoryComponents.pop(); + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; } - // Find the component that differs - var joinStartIndex; - for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { - break; - } - } - // Get the relative path - if (joinStartIndex) { - var relativePath = ""; - var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); - for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (directoryComponents[joinStartIndex] !== "") { - relativePath = relativePath + ".." + ts.directorySeparator; - } - } - return relativePath + relativePathComponents.join(ts.directorySeparator); - } - // Cant find the relative path, get the absolute path - var absolutePath = getNormalizedPathFromPathComponents(pathComponents); - if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { - absolutePath = "file:///" + absolutePath; - } - return absolutePath; + return getPathFromPathComponents(pathComponents); } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function getRelativePath(path, directoryPath, getCanonicalFileName) { - var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ensurePathIsRelative(relativePath); + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path; } - ts.getRelativePath = getRelativePath; - function ensurePathIsRelative(path) { - return !pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsRelative = ensurePathIsRelative; - function getBaseFileName(path) { - if (path === undefined) { - return undefined; - } - var i = path.lastIndexOf(ts.directorySeparator); - return i < 0 ? path : path.substring(i + 1); + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; } ts.getBaseFileName = getBaseFileName; - function combinePaths(path1, path2) { - if (!(path1 && path1.length)) - return path2; - if (!(path2 && path2.length)) - return path1; - if (getRootLength(path2) !== 0) - return path2; - if (path1.charAt(path1.length - 1) === ts.directorySeparator) - return path1 + path2; - return path1 + ts.directorySeparator + path2; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; } ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function removeTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) === ts.directorySeparator) { + if (hasTrailingDirectorySeparator(path)) { return path.substr(0, path.length - 1); } return path; } ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; function ensureTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) !== ts.directorySeparator) { + if (!hasTrailingDirectorySeparator(path)) { return path + ts.directorySeparator; } return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - function comparePaths(a, b, currentDirectory, ignoreCase) { + function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0 /* EqualTo */; if (a === undefined) return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; - a = removeTrailingDirectorySeparator(a); - b = removeTrailingDirectorySeparator(b); - var aComponents = getNormalizedPathComponents(a, currentDirectory); - var bComponents = getNormalizedPathComponents(b, currentDirectory); + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - var comparer = getStringComparer(ignoreCase); for (var i = 0; i < sharedLength; i++) { - var result = comparer(aComponents[i], bComponents[i]); + var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); if (result !== 0 /* EqualTo */) { return result; } } return compareValues(aComponents.length, bComponents.length); } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, getStringComparer(ignoreCase)); + } ts.comparePaths = comparePaths; function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } if (parent === undefined || child === undefined) return false; if (parent === child) return true; - parent = removeTrailingDirectorySeparator(parent); - child = removeTrailingDirectorySeparator(child); - if (parent === child) - return true; - var parentComponents = getNormalizedPathComponents(parent, currentDirectory); - var childComponents = getNormalizedPathComponents(child, currentDirectory); + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); if (childComponents.length < parentComponents.length) { return false; } - var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; + var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer; if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } @@ -4050,13 +4265,17 @@ var ts; ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { - var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { - return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; + function isJavaScriptLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } function hasJavaScriptFileExtension(fileName) { return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } @@ -4128,7 +4347,7 @@ var ts; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */]; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { var ext = extensionsToRemove_1[_i]; @@ -4149,9 +4368,14 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return (removeFileExtension(path) + newExtension); + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -4437,6 +4661,10 @@ var ts; return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } ts.extensionIsTypeScript = extensionIsTypeScript; + function resolutionExtensionIsTypeScriptOrJson(ext) { + return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -4457,14 +4685,34 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - function getAnyExtensionFromPath(path) { + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive); + } var baseFileName = getBaseFileName(path); var extensionIndex = baseFileName.lastIndexOf("."); if (extensionIndex >= 0) { return baseFileName.substring(extensionIndex); } + return ""; } ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -4566,12 +4814,12 @@ var ts; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { + var _a; return _a = {}, _a[PollingInterval.Low] = levels.Low, _a[PollingInterval.Medium] = levels.Medium, _a[PollingInterval.High] = levels.High, _a; - var _a; } var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); @@ -4936,6 +5184,7 @@ var ts; readDirectory: readDirectory, getModifiedTime: getModifiedTime, createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, getMemoryUsage: function () { if (global.gc) { global.gc(); @@ -5374,6 +5623,11 @@ var ts; hash.update(data); return hash.digest("hex"); } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -5685,7 +5939,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -6162,6 +6416,7 @@ var ts; Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -6345,6 +6600,17 @@ var ts; Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -6443,6 +6709,7 @@ var ts; Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -6506,6 +6773,12 @@ var ts; Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), }; })(ts || (ts = {})); var ts; @@ -8256,11 +8529,10 @@ var ts; } } function scanJSDocToken() { + startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; } - startPos = pos; - tokenPos = pos; var ch = text.charCodeAt(pos); pos++; switch (ch) { @@ -8666,7 +8938,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 294 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 298 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8868,12 +9140,12 @@ var ts; case 159 /* IndexSignature */: case 162 /* FunctionType */: case 163 /* ConstructorType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: case 235 /* InterfaceDeclaration */: case 236 /* TypeAliasDeclaration */: - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: case 233 /* FunctionDeclaration */: case 153 /* MethodDeclaration */: case 154 /* Constructor */: @@ -8881,6 +9153,9 @@ var ts; case 156 /* SetAccessor */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + case 287 /* JSDocSignature */: return true; default: ts.assertTypeIsNever(node); @@ -8903,6 +9178,12 @@ var ts; case 243 /* ImportDeclaration */: case 242 /* ImportEqualsDeclaration */: case 213 /* VariableStatement */: + case 234 /* ClassDeclaration */: + case 233 /* FunctionDeclaration */: + case 238 /* ModuleDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 237 /* EnumDeclaration */: return true; default: return false; @@ -8916,13 +9197,7 @@ var ts; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { - var current = node.parent; - while (current) { - if (isBlockScope(current, current.parent)) { - return current; - } - current = current.parent; - } + return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; // Return display name of an identifier @@ -9040,6 +9315,8 @@ var ts; case 155 /* GetAccessor */: case 156 /* SetAccessor */: case 236 /* TypeAliasDeclaration */: + case 151 /* PropertyDeclaration */: + case 150 /* PropertySignature */: errorNode = node.name; break; case 192 /* ArrowFunction */: @@ -9070,6 +9347,10 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; + } + ts.isJsonSourceFile = isJsonSourceFile; function isConstEnumDeclaration(node) { return node.kind === 237 /* EnumDeclaration */ && isConst(node); } @@ -9409,6 +9690,23 @@ var ts; }); } ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.isObjectLiteralExpression(expression) && expression; + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral && + ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -9786,6 +10084,10 @@ var ts; return node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJsonFile(node) { + return node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { return node && !!(node.flags & 2097152 /* JSDoc */); } @@ -10010,6 +10312,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243 /* ImportDeclaration */: case 249 /* ExportDeclaration */: @@ -10019,12 +10325,13 @@ var ts; case 186 /* CallExpression */: return node.parent; case 177 /* LiteralType */: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243 /* ImportDeclaration */: @@ -10073,12 +10380,20 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 281 /* JSDocFunctionType */ && + return node.kind === 283 /* JSDocFunctionType */ && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 296 /* JSDocTypedefTag */ || node.kind === 291 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && @@ -10100,6 +10415,8 @@ var ts; return v && v.initializer; case 151 /* PropertyDeclaration */: return node.initializer; + case 269 /* PropertyAssignment */: + return node.initializer; } } function getSingleVariableOfVariableStatement(node) { @@ -10113,9 +10430,9 @@ var ts; node.body.kind === 238 /* ModuleDeclaration */ && node.body; } - function getJSDocCommentsAndTags(node) { + function getJSDocCommentsAndTags(hostNode) { var result; - getJSDocCommentsAndTagsWorker(node); + getJSDocCommentsAndTagsWorker(hostNode); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; @@ -10130,8 +10447,7 @@ var ts; // * @returns {number} // */ // var x = function(name) { return name.length; } - if (parent.parent && - (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { + if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) { getJSDocCommentsAndTagsWorker(parent.parent); } if (parent.parent && parent.parent.parent && @@ -10140,8 +10456,8 @@ var ts; getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } - if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || - ts.isBinaryExpression(parent) && getSpecialPropertyAssignmentKind(parent) !== 0 /* None */ || + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */ || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */ || node.kind === 184 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 215 /* ExpressionStatement */) { getJSDocCommentsAndTagsWorker(parent); } @@ -10149,7 +10465,7 @@ var ts; if (node.kind === 148 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -10176,7 +10492,10 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - var host = getJSDocHost(node); + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || @@ -10185,19 +10504,9 @@ var ts; host; return decl && ts.isFunctionLike(decl) ? decl : undefined; } - ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; function getJSDocHost(node) { - while (node.parent.kind === 284 /* JSDocTypeLiteral */) { - if (node.parent.parent.kind === 292 /* JSDocTypedefTag */) { - node = node.parent.parent; - } - else { - // node.parent.parent is a type expression, child of a parameter type - node = node.parent.parent.parent; - } - } - ts.Debug.assert(node.parent.kind === 283 /* JSDocComment */); - return node.parent.parent; + return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent; } ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { @@ -10212,7 +10521,8 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282 /* JSDocVariadicType */; + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || type && type.kind === 284 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -10354,8 +10664,14 @@ var ts; if (ts.isDeclaration(name.parent)) { return name.parent.name === name; } - var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + else if (ts.isQualifiedName(name.parent)) { + var tag = name.parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + } + else { + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + } default: return false; } @@ -10735,7 +11051,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: return 0; case 203 /* SpreadElement */: return 1; @@ -11064,8 +11380,8 @@ var ts; }; } ts.createTextWriter = createTextWriter; - function getResolvedExternalModuleName(host, file) { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { @@ -11079,12 +11395,13 @@ var ts; /** * Resolves a local path to a path which is absolute to the base of the emit */ - function getExternalModuleNameFromPath(host, fileName) { + function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.removeFileExtension(relativePath); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { @@ -11178,7 +11495,8 @@ var ts; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { - if (signature.parameters.length) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { var thisParameter = signature.parameters[0]; if (parameterIsThisKeyword(thisParameter)) { return thisParameter; @@ -11263,6 +11581,9 @@ var ts; * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { + if (ts.isJSDocSignature(node)) { + return node.type && node.type.typeExpression && node.type.typeExpression.type; + } return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; @@ -11271,12 +11592,27 @@ var ts; * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ function getEffectiveTypeParameterDeclarations(node) { - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 285 /* JSDocComment */); + var templateTags = ts.flatMap(ts.filter(node.parent.tags, ts.isJSDocTemplateTag), function (tag) { return tag.typeParameters; }); + var templateTagNodes = templateTags; + templateTagNodes.pos = templateTagNodes.length > 0 ? ts.first(templateTagNodes).pos : node.pos; + templateTagNodes.end = templateTagNodes.length > 0 ? ts.last(templateTagNodes).end : node.end; + templateTagNodes.hasTrailingComma = false; + return templateTagNodes; + } + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; + // template tags are only available when a typedef isn't already using them + var tag = ts.find(ts.getJSDocTags(node), function (tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + }); + return (tag && tag.typeParameters) || ts.emptyArray; } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** @@ -12664,8 +13000,8 @@ var ts; break; case 71 /* Identifier */: return declaration; - case 293 /* JSDocPropertyTag */: - case 288 /* JSDocParameterTag */: { + case 297 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: { var name = declaration.name; if (name.kind === 145 /* QualifiedName */) { return name.right; @@ -12684,7 +13020,9 @@ var ts; return undefined; } } - case 292 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + return declaration.name; + case 296 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); case 248 /* ExportAssignment */: { var expression = declaration.expression; @@ -12817,7 +13155,9 @@ var ts; var tags = node.jsDocCache; // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); } return tags; } @@ -12935,6 +13275,11 @@ var ts; return node.kind === 159 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 156 /* SetAccessor */ || node.kind === 155 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { return node.kind === 160 /* TypePredicate */; @@ -13063,7 +13408,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296 /* PartiallyEmittedExpression */) { + while (node.kind === 300 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -13419,81 +13764,89 @@ var ts; ts.isBundle = isBundle; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 275 /* JSDocTypeExpression */; + return node.kind === 277 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 276 /* JSDocAllType */; + return node.kind === 278 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 277 /* JSDocUnknownType */; + return node.kind === 279 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 278 /* JSDocNullableType */; + return node.kind === 280 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 279 /* JSDocNonNullableType */; + return node.kind === 281 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 280 /* JSDocOptionalType */; + return node.kind === 282 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 281 /* JSDocFunctionType */; + return node.kind === 283 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 282 /* JSDocVariadicType */; + return node.kind === 284 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 283 /* JSDocComment */; + return node.kind === 285 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 286 /* JSDocAugmentsTag */; + return node.kind === 289 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 287 /* JSDocClassTag */; + return node.kind === 290 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { - return node.kind === 288 /* JSDocParameterTag */; + return node.kind === 292 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 289 /* JSDocReturnTag */; + return node.kind === 293 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 290 /* JSDocTypeTag */; + return node.kind === 294 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 291 /* JSDocTemplateTag */; + return node.kind === 295 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 292 /* JSDocTypedefTag */; + return node.kind === 296 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 293 /* JSDocPropertyTag */; + return node.kind === 297 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 293 /* JSDocPropertyTag */ || node.kind === 288 /* JSDocParameterTag */; + return node.kind === 297 /* JSDocPropertyTag */ || node.kind === 292 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 284 /* JSDocTypeLiteral */; + return node.kind === 286 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 291 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 287 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); // Node tests // @@ -13502,7 +13855,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 294 /* SyntaxList */; + return n.kind === 298 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13647,10 +14000,11 @@ var ts; switch (kind) { case 152 /* MethodSignature */: case 157 /* CallSignature */: + case 287 /* JSDocSignature */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: case 162 /* FunctionType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: case 163 /* ConstructorType */: return true; default: @@ -13734,13 +14088,13 @@ var ts; || kind === 95 /* NullKeyword */ || kind === 131 /* NeverKeyword */ || kind === 206 /* ExpressionWithTypeArguments */ - || kind === 276 /* JSDocAllType */ - || kind === 277 /* JSDocUnknownType */ - || kind === 278 /* JSDocNullableType */ - || kind === 279 /* JSDocNonNullableType */ - || kind === 280 /* JSDocOptionalType */ - || kind === 281 /* JSDocFunctionType */ - || kind === 282 /* JSDocVariadicType */; + || kind === 278 /* JSDocAllType */ + || kind === 279 /* JSDocUnknownType */ + || kind === 280 /* JSDocNullableType */ + || kind === 281 /* JSDocNonNullableType */ + || kind === 282 /* JSDocOptionalType */ + || kind === 283 /* JSDocFunctionType */ + || kind === 284 /* JSDocVariadicType */; } /** * Node test that determines whether a node is a valid type node. @@ -13962,8 +14316,8 @@ var ts; case 203 /* SpreadElement */: case 207 /* AsExpression */: case 205 /* OmittedExpression */: - case 297 /* CommaListExpression */: - case 296 /* PartiallyEmittedExpression */: + case 301 /* CommaListExpression */: + case 300 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13977,12 +14331,12 @@ var ts; ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 296 /* PartiallyEmittedExpression */; + return node.kind === 300 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 295 /* NotEmittedStatement */; + return node.kind === 299 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -14093,7 +14447,9 @@ var ts; || kind === 236 /* TypeAliasDeclaration */ || kind === 147 /* TypeParameter */ || kind === 231 /* VariableDeclaration */ - || kind === 292 /* JSDocTypedefTag */; + || kind === 296 /* JSDocTypedefTag */ + || kind === 291 /* JSDocCallbackTag */ + || kind === 297 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { return kind === 233 /* FunctionDeclaration */ @@ -14128,14 +14484,14 @@ var ts; || kind === 213 /* VariableStatement */ || kind === 218 /* WhileStatement */ || kind === 225 /* WithStatement */ - || kind === 295 /* NotEmittedStatement */ - || kind === 299 /* EndOfDeclarationMarker */ - || kind === 298 /* MergeDeclarationMarker */; + || kind === 299 /* NotEmittedStatement */ + || kind === 303 /* EndOfDeclarationMarker */ + || kind === 302 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 147 /* TypeParameter */) { - return node.parent.kind !== 291 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 295 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -14230,18 +14586,18 @@ var ts; /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 275 /* FirstJSDocNode */ && node.kind <= 293 /* LastJSDocNode */; + return node.kind >= 277 /* FirstJSDocNode */ && node.kind <= 297 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 283 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node); + return node.kind === 285 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 285 /* FirstJSDocTagNode */ && node.kind <= 293 /* LastJSDocTagNode */; + return node.kind >= 288 /* FirstJSDocTagNode */ && node.kind <= 297 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -14292,12 +14648,12 @@ var ts; case 231 /* VariableDeclaration */: case 233 /* FunctionDeclaration */: case 236 /* TypeAliasDeclaration */: - case 275 /* JSDocTypeExpression */: - case 278 /* JSDocNullableType */: - case 279 /* JSDocNonNullableType */: - case 280 /* JSDocOptionalType */: - case 281 /* JSDocFunctionType */: - case 282 /* JSDocVariadicType */: + case 277 /* JSDocTypeExpression */: + case 280 /* JSDocNullableType */: + case 281 /* JSDocNonNullableType */: + case 282 /* JSDocOptionalType */: + case 283 /* JSDocFunctionType */: + case 284 /* JSDocVariadicType */: return true; } return false; @@ -14787,7 +15143,7 @@ var ts; return visitNode(cbNode, node.expression); case 252 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 254 /* JsxElement */: return visitNode(cbNode, node.openingElement) || @@ -14814,23 +15170,23 @@ var ts; visitNode(cbNode, node.expression); case 257 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 275 /* JSDocTypeExpression */: + case 277 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 279 /* JSDocNonNullableType */: + case 281 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 278 /* JSDocNullableType */: + case 280 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 280 /* JSDocOptionalType */: + case 282 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 283 /* JSDocComment */: + case 285 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 288 /* JSDocParameterTag */: - case 293 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: + case 297 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -14839,17 +15195,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 289 /* JSDocReturnTag */: + case 293 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 290 /* JSDocTypeTag */: + case 294 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 286 /* JSDocAugmentsTag */: + case 289 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 292 /* JSDocTypedefTag */: + case 296 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 275 /* JSDocTypeExpression */) { + node.typeExpression.kind === 277 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -14857,7 +15213,16 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 284 /* JSDocTypeLiteral */: + case 291 /* JSDocCallbackTag */: + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 287 /* JSDocSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 286 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -14865,7 +15230,7 @@ var ts; } } return; - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -14873,7 +15238,13 @@ var ts; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; @@ -15033,6 +15404,13 @@ var ts; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + return result_1; + } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); @@ -15050,25 +15428,57 @@ var ts; return isInvalid ? entityName : undefined; } Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function parseJsonText(fileName, sourceText) { - initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); // Set source file so that errors will be reported with this file name sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); - var result = sourceFile; // Prime the scanner. nextToken(); + var pos = getNodePos(); if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); sourceFile.endOfFileToken = parseTokenNode(); } - else if (token() === 17 /* OpenBraceToken */ || - lookAhead(function () { return token() === 9 /* StringLiteral */; })) { - result.jsonObject = parseObjectLiteralExpression(); + else { + var statement = createNode(215 /* ExpressionStatement */); + switch (token()) { + case 21 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 38 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); } - else { - parseExpected(17 /* OpenBraceToken */); + if (setParentNodes) { + fixupParentReferences(sourceFile); } sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; clearState(); return result; } @@ -15092,9 +15502,11 @@ var ts; switch (scriptKind) { case 1 /* JS */: case 2 /* JSX */: - case 6 /* JSON */: contextFlags = 65536 /* JavaScriptFile */; break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; default: contextFlags = 0 /* None */; break; @@ -16340,9 +16752,9 @@ var ts; return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(276 /* JSDocAllType */); + var result = createNode(278 /* JSDocAllType */); if (postFixEquals) { - return createJSDocPostfixType(280 /* JSDocOptionalType */, result); + return createJSDocPostfixType(282 /* JSDocOptionalType */, result); } else { nextToken(); @@ -16350,7 +16762,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(279 /* JSDocNonNullableType */); + var result = createNode(281 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -16374,18 +16786,18 @@ var ts; token() === 29 /* GreaterThanToken */ || token() === 58 /* EqualsToken */ || token() === 49 /* BarToken */) { - var result = createNode(277 /* JSDocUnknownType */, pos); + var result = createNode(279 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(278 /* JSDocNullableType */, pos); + var result = createNode(280 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(281 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(283 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); @@ -16407,12 +16819,12 @@ var ts; var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseType(); if (dotdotdot) { - var variadic = createNode(282 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(284 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } if (token() === 58 /* EqualsToken */) { - return createJSDocPostfixType(280 /* JSDocOptionalType */, type); + return createJSDocPostfixType(282 /* JSDocOptionalType */, type); } return type; } @@ -16496,15 +16908,19 @@ var ts; node.initializer = parseInitializer(); return finishNode(node); } + /** + * @returns If return type parsing succeeds + */ function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */)); - } - function parseReturnType(returnToken, isType) { - return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + return signature.type !== undefined; + } + return true; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36 /* EqualsGreaterThanToken */) { @@ -16783,6 +17199,9 @@ var ts; var node = createNode(172 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); + if (!node.type) { + return undefined; + } parseExpected(20 /* CloseParenToken */); return finishNode(node); } @@ -16791,7 +17210,12 @@ var ts; if (kind === 163 /* ConstructorType */) { parseExpected(94 /* NewKeyword */); } - fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + if (!fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */ | (sourceFile.languageVariant === 1 /* JSX */ ? 8 /* RequireCompleteParameterList */ : 0), node)) { + return undefined; + } + if (!node.parameters) { + return undefined; + } return finishNode(node); } function parseKeywordAndNoDot() { @@ -16947,14 +17371,14 @@ var ts; while (!scanner.hasPrecedingLineBreak()) { switch (token()) { case 51 /* ExclamationToken */: - type = createJSDocPostfixType(279 /* JSDocNonNullableType */, type); + type = createJSDocPostfixType(281 /* JSDocNonNullableType */, type); break; case 55 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createJSDocPostfixType(278 /* JSDocNullableType */, type); + type = createJSDocPostfixType(280 /* JSDocNullableType */, type); break; case 21 /* OpenBracketToken */: parseExpected(21 /* OpenBracketToken */); @@ -17518,7 +17942,7 @@ var ts; // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] if (token() === 120 /* AsyncKeyword */) { nextToken(); - // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { return 0 /* False */; @@ -17542,7 +17966,9 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node); + if (!fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node)) { + return undefined; + } // If we couldn't get parameters, we definitely could not parse out an arrow function. if (!node.parameters) { return undefined; @@ -19905,7 +20331,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos()); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -19925,6 +20351,7 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var _a; var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -19942,7 +20369,6 @@ var ts; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; - var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; var JSDocState; @@ -19953,8 +20379,9 @@ var ts; })(JSDocState || (JSDocState = {})); var PropertyLikeParse; (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; @@ -20002,7 +20429,7 @@ var ts; case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); - parseTag(indent); + addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning // for malformed examples like `/** @param {string} x @returns {number} the length */` @@ -20076,12 +20503,29 @@ var ts; } } function createJSDocComment() { - var result = createNode(283 /* JSDocComment */, start); + var result = createNode(285 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { nextJSDocToken(); } @@ -20110,8 +20554,7 @@ var ts; case "arg": case "argument": case "param": - addTag(parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */, indent)); - return; + return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); case "return": case "returns": tag = parseReturnTag(atToken, tagName); @@ -20123,7 +20566,10 @@ var ts; tag = parseTypeTag(atToken, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(atToken, tagName, indent); break; default: tag = parseUnknownTag(atToken, tagName); @@ -20137,8 +20583,11 @@ var ts; // a badly malformed tag should not be added to the list of tags return; } - tag.comment = parseTagComments(indent + tag.end - tag.pos); - addTag(tag); + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; } function parseTagComments(indent) { var comments = []; @@ -20201,12 +20650,15 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { - var result = createNode(285 /* JSDocTag */, atToken.pos); + var result = createNode(288 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } function addTag(tag) { + if (!tag) { + return; + } if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -20257,9 +20709,9 @@ var ts; if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var result = target === 1 /* Parameter */ ? - createNode(288 /* JSDocParameterTag */, atToken.pos) : - createNode(293 /* JSDocPropertyTag */, atToken.pos); + var result = target === 1 /* Property */ ? + createNode(297 /* JSDocPropertyTag */, atToken.pos) : + createNode(292 /* JSDocParameterTag */, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -20279,18 +20731,18 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name, target) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 288 /* JSDocParameterTag */ || child.kind === 293 /* JSDocPropertyTag */) { + if (child.kind === 292 /* JSDocParameterTag */ || child.kind === 297 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; if (typeExpression.type.kind === 166 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; @@ -20301,27 +20753,27 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 293 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(289 /* JSDocReturnTag */, atToken.pos); + var result = createNode(293 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 290 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 294 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(290 /* JSDocTypeTag */, atToken.pos); + var result = createNode(294 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var result = createNode(286 /* JSDocAugmentsTag */, atToken.pos); + var result = createNode(289 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); @@ -20349,32 +20801,23 @@ var ts; return node; } function parseClassTag(atToken, tagName) { - var tag = createNode(287 /* JSDocClassTag */, atToken.pos); + var tag = createNode(290 /* JSDocClassTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); } - function parseTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(292 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(296 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { - // if node is identifier - use it as name - // otherwise use name of the rightmost part that we were able to parse - typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); skipWhitespace(); + typedefTag.comment = parseTagComments(indent); typedefTag.typeExpression = typeExpression; + var end; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; @@ -20382,9 +20825,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 290 /* JSDocTypeTag */) { + if (child.kind === 294 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -20403,23 +20846,68 @@ var ts; typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; } } - return finishNode(typedefTag); - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); - return finishNode(jsDocNamespaceNode); + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { + var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } - if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { - typeNameOrNamespaceName.isInJSDocNamespace = true; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(atToken, tagName, indent) { + var callbackTag = createNode(291 /* JSDocCallbackTag */, atToken.pos); + callbackTag.atToken = atToken; + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var start = scanner.getStartPos(); + var jsdocSignature = createNode(287 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (token() === 57 /* AtToken */) { + nextJSDocToken(); + var tag = parseTag(indent); + if (tag && tag.kind === 293 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; } - return typeNameOrNamespaceName; } } function escapedTextsEqual(a, b) { @@ -20435,7 +20923,7 @@ var ts; return a.escapedText === b.escapedText; } function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(0 /* Property */); + return parseChildParameterOrPropertyTag(1 /* Property */); } function parseChildParameterOrPropertyTag(target, name) { var canParseTag = true; @@ -20445,7 +20933,8 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 288 /* JSDocParameterTag */ && + if (child && child.kind === 292 /* JSDocParameterTag */ && + target !== 4 /* CallbackParameter */ && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -20484,20 +20973,20 @@ var ts; var t; switch (tagName.escapedText) { case "type": - return target === 0 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - t = 0 /* Property */; + t = 1 /* Property */; break; case "arg": case "argument": case "param": - t = 1 /* Parameter */; + t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; default: return false; } - if (target !== t) { + if (!(target & t)) { return false; } var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); @@ -20530,7 +21019,7 @@ var ts; break; } } - var result = createNode(291 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(295 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -20579,7 +21068,7 @@ var ts; var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); var result = createNode(71 /* Identifier */, pos); - result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); return result; @@ -21383,7 +21872,7 @@ var ts; var thisParentContainer; // Container one level up var blockScopeContainer; var lastContainer; - var delayedTypedefs; + var delayedTypeAliases; var seenThisKeyword; // state used by control flow analysis var currentFlow; @@ -21441,7 +21930,7 @@ var ts; thisParentContainer = undefined; blockScopeContainer = undefined; lastContainer = undefined; - delayedTypedefs = undefined; + delayedTypeAliases = undefined; seenThisKeyword = false; currentFlow = undefined; currentBreakTarget = undefined; @@ -21515,6 +22004,7 @@ var ts; return "__constructor" /* Constructor */; case 162 /* FunctionType */: case 157 /* CallSignature */: + case 287 /* JSDocSignature */: return "__call" /* Call */; case 163 /* ConstructorType */: case 158 /* ConstructSignature */: @@ -21523,6 +22013,10 @@ var ts; return "__index" /* Index */; case 249 /* ExportDeclaration */: return "__export" /* ExportStar */; + case 273 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; case 199 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { // module.exports = ... @@ -21530,18 +22024,15 @@ var ts; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); case 148 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 281 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 283 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; - case 292 /* JSDocTypedefTag */: - var name_2 = ts.getNameOfJSDocTypedef(node); - return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } } function getDisplayName(node) { @@ -21679,9 +22170,9 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (node.kind === 292 /* JSDocTypedefTag */) + if (ts.isJSDocTypeAlias(node)) ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypedefTag(node)) { + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } @@ -21846,23 +22337,6 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - // Binding of JsDocComment should be done before the current block scope container changes. - // because the scope of JsDocComment should not be affected by whether the current node is a - // container or not. - if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var j = _a[_i]; - bind(j); - } - } - else { - for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { - var j = _c[_b]; - setParentPointers(node, j); - } - } - } if (checkUnreachable(node)) { bindEachChild(node); return; @@ -21928,11 +22402,9 @@ var ts; case 186 /* CallExpression */: bindCallExpressionFlow(node); break; - case 283 /* JSDocComment */: - bindJSDocComment(node); - break; - case 292 /* JSDocTypedefTag */: - bindJSDocTypedefTag(node); + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 273 /* SourceFile */: @@ -21947,6 +22419,7 @@ var ts; bindEachChild(node); break; } + bindJSDoc(node); } function isNarrowingExpression(expr) { switch (expr.kind) { @@ -22548,23 +23021,10 @@ var ts; bindInitializedVariableFlow(node); } } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 292 /* JSDocTypedefTag */) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - // if the node has a fullName "A.B.C", that means symbol "C" was already bound - // when we visit "fullName"; so when we visit the name "C" as the next child of - // the jsDocTypedefTag, we should skip binding it. - if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { - return; - } - bind(n); - }); + function bindJSDocTypeAlias(node) { + if (node.fullName) { + setParentPointers(node, node.fullName); + } } function bindCallExpressionFlow(node) { // If the target of the call expression is a function expression or arrow function we have @@ -22596,7 +23056,7 @@ var ts; case 237 /* EnumDeclaration */: case 183 /* ObjectLiteralExpression */: case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: + case 286 /* JSDocTypeLiteral */: case 262 /* JsxAttributes */: return 1 /* IsContainer */; case 235 /* InterfaceDeclaration */: @@ -22618,7 +23078,8 @@ var ts; case 155 /* GetAccessor */: case 156 /* SetAccessor */: case 157 /* CallSignature */: - case 281 /* JSDocFunctionType */: + case 287 /* JSDocSignature */: + case 283 /* JSDocFunctionType */: case 162 /* FunctionType */: case 158 /* ConstructSignature */: case 159 /* IndexSignature */: @@ -22680,7 +23141,7 @@ var ts; case 237 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: + case 286 /* JSDocTypeLiteral */: case 183 /* ObjectLiteralExpression */: case 235 /* InterfaceDeclaration */: case 262 /* JsxAttributes */: @@ -22694,6 +23155,7 @@ var ts; case 163 /* ConstructorType */: case 157 /* CallSignature */: case 158 /* ConstructSignature */: + case 287 /* JSDocSignature */: case 159 /* IndexSignature */: case 153 /* MethodDeclaration */: case 152 /* MethodSignature */: @@ -22703,7 +23165,9 @@ var ts; case 233 /* FunctionDeclaration */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: case 236 /* TypeAliasDeclaration */: case 176 /* MappedType */: // All the children of these container types are never visible through another @@ -22878,22 +23342,35 @@ var ts; bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); } function delayedBindJSDocTypedefTag() { - if (!delayedTypedefs) { + if (!delayedTypeAliases) { return; } var saveContainer = container; var saveLastContainer = lastContainer; var saveBlockScopeContainer = blockScopeContainer; var saveParent = parent; - for (var _i = 0, delayedTypedefs_1 = delayedTypedefs; _i < delayedTypedefs_1.length; _i++) { - var delay = delayedTypedefs_1[_i]; - (container = delay.container, lastContainer = delay.lastContainer, blockScopeContainer = delay.blockScopeContainer, parent = delay.parent); - bindBlockScopedDeclaration(delay.typedef, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } } container = saveContainer; lastContainer = saveLastContainer; blockScopeContainer = saveBlockScopeContainer; parent = saveParent; + currentFlow = saveCurrentFlow; } // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized // check for reserved words used as identifiers in strict mode code. @@ -23045,8 +23522,6 @@ var ts; // Here the current node is "foo", which is a container, but the scope of "MyType" should // not be inside "foo". Therefore we always bind @typedef before bind the parent node, // and skip binding this tag later when binding all the other jsdoc tags. - if (ts.isInJavaScriptFile(node)) - bindJSDocTypedefTagIfAny(node); // First we bind declaration nodes to a symbol if possible. We'll both create a symbol // and then potentially add the symbol to an appropriate symbol table. Possible // destination symbol tables are: @@ -23077,25 +23552,22 @@ var ts; } else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + bindJSDoc(node); } inStrictMode = saveInStrictMode; } - function bindJSDocTypedefTagIfAny(node) { - if (!ts.hasJSDocNodes(node)) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 292 /* JSDocTypedefTag */) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); } } } @@ -23130,7 +23602,7 @@ var ts; // current "blockScopeContainer" needs to be set to its immediate namespace parent. if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 292 /* JSDocTypedefTag */) { + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); @@ -23232,11 +23704,12 @@ var ts; case 156 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); case 162 /* FunctionType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: + case 287 /* JSDocSignature */: case 163 /* ConstructorType */: return bindFunctionOrConstructorType(node); case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: + case 286 /* JSDocTypeLiteral */: case 176 /* MappedType */: return bindAnonymousTypeWorker(node); case 183 /* ObjectLiteralExpression */: @@ -23292,24 +23765,23 @@ var ts; // falls through case 239 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 288 /* JSDocParameterTag */: - if (node.parent.kind !== 284 /* JSDocTypeLiteral */) { + case 292 /* JSDocParameterTag */: + if (node.parent.kind === 287 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 286 /* JSDocTypeLiteral */) { break; } // falls through - case 293 /* JSDocPropertyTag */: + case 297 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 280 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 282 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 292 /* JSDocTypedefTag */: { - var fullName = node.fullName; - if (!fullName || fullName.kind === 71 /* Identifier */) { - (delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node, container: container, lastContainer: lastContainer, blockScopeContainer: blockScopeContainer, parent: parent }); - } - break; - } + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } function bindPropertyWorker(node) { @@ -23323,6 +23795,13 @@ var ts; if (ts.isExternalModule(file)) { bindSourceFileAsExternalModule(); } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } } function bindSourceFileAsExternalModule() { bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); @@ -23662,6 +24141,9 @@ var ts; } } function bindParameter(node) { + if (node.kind === 292 /* JSDocParameterTag */ && container.kind !== 287 /* JSDocSignature */) { + return; + } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) @@ -23720,24 +24202,30 @@ var ts; : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } function getInferTypeContainer(node) { - while (node) { - var parent_2 = node.parent; - if (parent_2 && parent_2.kind === 170 /* ConditionalType */ && parent_2.extendsType === node) { - return parent_2; - } - node = parent_2; - } - return undefined; + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; } function bindTypeParameter(node) { - if (node.parent.kind === 171 /* InferType */) { - var container_1 = getInferTypeContainer(node.parent); + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); if (container_1) { if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 171 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); } @@ -23999,7 +24487,7 @@ var ts; else { // A ClassDeclaration is ES6 syntax. transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is + // A class with a parameter property assignment, property initializer, computed property name, or decorator is // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. @@ -24136,9 +24624,9 @@ var ts; function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; - // If the PropertyDeclaration has an initializer, we need to inform its ancestor + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. - if (node.initializer) { + if (node.initializer || ts.isComputedPropertyName(node.name)) { transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -24362,7 +24850,7 @@ var ts; break; case 189 /* TypeAssertionExpression */: case 207 /* AsExpression */: - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; @@ -24634,7 +25122,7 @@ var ts; return 940049729 /* BindingPatternExcludes */; case 189 /* TypeAssertionExpression */: case 207 /* AsExpression */: - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: case 190 /* ParenthesizedExpression */: case 97 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; @@ -24652,7 +25140,7 @@ var ts; */ function setParentPointers(parent, child) { child.parent = parent; - ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); } })(ts || (ts = {})); /** @internal */ @@ -24850,7 +25338,8 @@ var ts; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { @@ -24894,7 +25383,13 @@ var ts; function readJson(path, host) { try { var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; } catch (e) { // gracefully handle if readFile fails or returns not JSON @@ -25425,7 +25920,11 @@ var ts; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + var result = jsOnly ? + tryResolve(Extensions.JavaScript) : + (tryResolve(Extensions.TypeScript) || + tryResolve(Extensions.JavaScript) || + (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); @@ -25480,7 +25979,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); if (!directoryProbablyExists(parentOfCandidate, state.host)) { @@ -25565,6 +26064,10 @@ var ts; * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (extensions === Extensions.Json) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -25585,9 +26088,9 @@ var ts; function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + var directory_1 = ts.getDirectoryPath(candidate); + if (directory_1) { + onlyRecordFailures = !directoryProbablyExists(directory_1, state.host); } } switch (extensions) { @@ -25597,6 +26100,8 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.Json: + return tryExtension(".json" /* Json */); } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); @@ -25649,8 +26154,11 @@ var ts; } else { var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string") { - subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */; + if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { + var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; } else { subModuleName = "index.d.ts"; @@ -25683,9 +26191,18 @@ var ts; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); if (!file) { - return undefined; + if (extensions === Extensions.TypeScript) { + // When resolving typescript modules, try resolving using main field as well + file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + if (!file) { + return undefined; + } + } + else { + return undefined; + } } var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); @@ -25718,6 +26235,8 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.Json: + return extension === ".json" /* Json */; case Extensions.TypeScript: return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; case Extensions.DtsOnly: @@ -25788,7 +26307,7 @@ var ts; if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript) { + if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { @@ -26213,7 +26732,7 @@ var ts; checkSourceFile(file); var diagnostics = []; ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); - checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { if (!unusedIsError(kind)) { diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } @@ -26283,6 +26802,7 @@ var ts; var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); @@ -26327,8 +26847,6 @@ var ts; var deferredGlobalExtractSymbol; var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name - var potentiallyUnusedIdentifiers; // Potentially unused identifiers in the source file currently being checked. - var seenPotentiallyUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -26639,17 +27157,17 @@ var ts; } function getJsxNamespace(location) { if (location) { - var file = ts.getSourceFileOfNode(location); - if (file) { - if (file.localJsxNamespace) { - return file.localJsxNamespace; + var file_1 = ts.getSourceFileOfNode(location); + if (file_1) { + if (file_1.localJsxNamespace) { + return file_1.localJsxNamespace; } - var jsxPragma = file.pragmas.get("jsx"); + var jsxPragma = file_1.pragmas.get("jsx"); if (jsxPragma) { var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; - file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); - if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + if (file_1.localJsxFactory) { + return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText; } } } @@ -26761,6 +27279,8 @@ var ts; function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* JSContainer */) { + var targetValueDeclaration = target.valueDeclaration; + ts.Debug.assert(!!(target.flags & 33554432 /* Transient */)); // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums @@ -26786,7 +27306,12 @@ var ts; } if ((source.flags | target.flags) & 67108864 /* JSContainer */) { var sourceInitializer = ts.getJSInitializerSymbol(source); - var targetInitializer = ts.getJSInitializerSymbol(target); + var init = ts.getDeclaredJavascriptInitializer(targetValueDeclaration) || ts.getAssignedJavascriptInitializer(targetValueDeclaration); + var targetInitializer = init && init.symbol ? init.symbol : target; + if (!(targetInitializer.flags & 33554432 /* Transient */)) { + var mergedInitializer = getMergedSymbol(targetInitializer); + targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer; + } if (sourceInitializer !== source || targetInitializer !== target) { mergeSymbol(targetInitializer, sourceInitializer); } @@ -27070,7 +27595,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 283 /* JSDocComment */) { + if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 285 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -27269,6 +27794,12 @@ var ts; location = location.parent; } break; + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + lastLocation = location; + location = ts.getJSDocHost(location).parent; + continue; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -27384,9 +27915,11 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (decl.kind === 147 /* TypeParameter */ && parent === container) { - return true; + if (decl.kind === 147 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + } } } return false; @@ -27597,8 +28130,8 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); - var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + var file_2 = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file_2, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -27850,7 +28383,7 @@ var ts; var symbol; if (name.kind === 71 /* Identifier */) { var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSPrototype(name, meaning) : undefined; + var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -27859,40 +28392,40 @@ var ts; else if (name.kind === 145 /* QualifiedName */ || name.kind === 184 /* PropertyAccessExpression */) { var left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); - if (!namespace || ts.nodeIsMissing(right)) { + var namespace_1 = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace_1 || ts.nodeIsMissing(right)) { return undefined; } - else if (namespace === unknownSymbol) { - return namespace; + else if (namespace_1 === unknownSymbol) { + return namespace_1; } if (ts.isInJavaScriptFile(name)) { - var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); + var initializer = ts.getDeclaredJavascriptInitializer(namespace_1.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace_1.valueDeclaration); if (initializer) { - namespace = getSymbolOfNode(initializer); + namespace_1 = getSymbolOfNode(initializer); } // Currently, IIFEs may not have a symbol and we don't know about their contents. Give up in this case. - if (!namespace) { + if (!namespace_1) { return undefined; } - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + if (namespace_1.valueDeclaration && + ts.isVariableDeclaration(namespace_1.valueDeclaration) && + namespace_1.valueDeclaration.initializer && + isCommonJsRequire(namespace_1.valueDeclaration.initializer)) { + var moduleName = namespace_1.valueDeclaration.initializer.arguments[0]; var moduleSym = resolveExternalModuleName(moduleName, moduleName); if (moduleSym) { var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; + namespace_1 = resolvedModuleSymbol; } } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getSymbol(getExportsOfSymbol(namespace_1), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace_1), ts.declarationNameToString(right)); } return undefined; } @@ -27904,24 +28437,37 @@ var ts; return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } /** - * For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSPrototype(name, meaning) { - if (isJSDocTypeReference(name.parent) && ts.isJSDocTag(name.parent.parent.parent)) { - var host_1 = ts.getJSDocHost(name.parent.parent.parent); - if (ts.isExpressionStatement(host_1) && - ts.isBinaryExpression(host_1.expression) && - ts.getSpecialPropertyAssignmentKind(host_1.expression) === 3 /* PrototypeProperty */) { - var symbol = getSymbolOfNode(host_1.expression.left); - if (symbol) { - var secondaryLocation = symbol.parent.valueDeclaration; - return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); - } + function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } + function getJSSpecialAssignmentLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + var symbol = getSymbolOfNode(host.expression.left); + return symbol && symbol.parent.valueDeclaration; + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -27970,7 +28516,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -27982,7 +28528,22 @@ var ts; return undefined; } if (moduleNotFoundError) { - // report errors only if it was requested + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } if (resolutionDiagnostic) { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } @@ -28429,7 +28990,7 @@ var ts; * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { + if (symbol && enclosingDeclaration) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { @@ -28446,6 +29007,14 @@ var ts; } return hasAccessibleDeclarations; } + else { + if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. // It could be a qualified symbol and hence verify the path // e.g.: @@ -28511,6 +29080,11 @@ var ts; isDeclarationVisible(declaration.parent.parent.parent)) { return addVisibleAlias(declaration, declaration.parent.parent); } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } // Declaration is not visible return false; } @@ -28678,7 +29252,7 @@ var ts; flags: flags, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined, + visitedSymbols: undefined, inferTypeParameters: undefined }; } @@ -28770,16 +29344,25 @@ var ts; } if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { - return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 32768 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { - var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name, typeArgumentNodes); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); } if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) { var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types; @@ -28828,14 +29411,26 @@ var ts; ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; + var id; if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); if (isJavaScriptConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; @@ -28847,7 +29442,7 @@ var ts; shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, 67216319 /* Value */); } - else if (ts.contains(context.symbolStack, symbol)) { + else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { @@ -28861,19 +29456,13 @@ var ts; else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.symbolStack) { - context.symbolStack = []; - } - var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - return createTypeNodeFromObjectType(type); - } - else { - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + if (!context.visitedSymbols) { + context.visitedSymbols = ts.createMap(); } + context.visitedSymbols.set(id, true); + var result = createTypeNodeFromObjectType(type); + context.visitedSymbols.delete(id); + return result; } } else { @@ -28890,7 +29479,7 @@ var ts; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed } } @@ -28922,11 +29511,6 @@ var ts; var typeLiteralNode = ts.createTypeLiteralNode(members); return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } - function symbolToTypeReferenceName(symbol) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); - return entityName; - } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { @@ -28959,7 +29543,7 @@ var ts; else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = void 0; + var resultType = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -28973,55 +29557,65 @@ var ts; // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); - var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); - var namePart = symbolToTypeReferenceName(parent); - (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); - } - else { - qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); - } + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } } } - var entityName = void 0; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } var typeArgumentNodes = void 0; if (typeArguments.length > 0) { var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } - if (typeArgumentNodes) { - var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; - lastIdentifier.typeArguments = undefined; - } - return ts.createTypeReferenceNode(entityName, typeArgumentNodes); + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } } - function addToQualifiedNameMissingRightIdentifier(left, right) { - ts.Debug.assert(left.right === undefined); - if (right.kind === 71 /* Identifier */) { - left.right = right; - return left; + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; } - var rightPart = right; - while (rightPart.left.kind !== 71 /* Identifier */) { - rightPart = rightPart.left; + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; } - left.right = rightPart.left; - rightPart.left = left; - return right; + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; } function createTypeNodesFromResolvedType(resolvedType) { var typeElements = []; @@ -29168,32 +29762,47 @@ var ts; } return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148 /* Parameter */); - ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 292 /* JSDocParameterTag */); + } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; + var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - cloneBindingName(parameterDeclaration.name) : + parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 145 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -29213,7 +29822,7 @@ var ts; } } } - function lookupSymbolChain(symbol, context, meaning) { + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; @@ -29249,7 +29858,7 @@ var ts; // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; @@ -29281,22 +29890,54 @@ var ts; } return typeParameterNodes; } - function symbolToTypeNode(symbol, context, meaning) { - var chain = lookupSymbolChain(symbol, context, meaning); + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module context.flags |= 16777216 /* InInitialEntityName */; var rootName = getNameOfSymbolAsWritten(chain[0], context); context.flags ^= 16777216 /* InInitialEntityName */; var isTypeOf = meaning === 67216319 /* Value */; if (ambientModuleSymbolRegex.test(rootName)) { // module is root, must use `ImportTypeNode` - var nonRootParts = chain.length > 1 ? createEntityNameFromSymbolChain(chain, chain.length - 1, 1) : undefined; - var typeParameterNodes = lookupTypeParameterNodes(chain, 0, context); - return ts.createImportTypeNode(ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))), nonRootParts, typeParameterNodes, isTypeOf); + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))); + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } } - var entityName = createEntityNameFromSymbolChain(chain, chain.length - 1, 0); - return isTypeOf ? ts.createTypeQueryNode(entityName) : ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); - function createEntityNameFromSymbolChain(chain, index, stopper) { - var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; @@ -29305,9 +29946,27 @@ var ts; if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); identifier.symbol = symbol; - return index > stopper ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1, stopper), identifier) : identifier; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; } } function symbolToName(symbol, context, meaning, expectsIdentifier) { @@ -29456,6 +30115,24 @@ var ts; return "default"; } if (symbol.declarations && symbol.declarations.length) { + if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { + var file_3 = ts.getDeclarationOfKind(symbol, 273 /* SourceFile */); + if (!file_3 || !context.tracker.moduleResolverHost) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl); + } + } + } + // ambient module, just use declaration/symbol name (fallthrough) + } + else { + return "\"" + ts.getResolvedExternalModuleName(context.tracker.moduleResolverHost, file_3, ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration))) + "\""; + } + } var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { @@ -29497,6 +30174,11 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); case 181 /* BindingElement */: return isDeclarationVisible(node.parent.parent); case 231 /* VariableDeclaration */: @@ -30209,7 +30891,7 @@ var ts; if (symbol.flags & 4194304 /* Prototype */) { return links.type = getTypeOfPrototypeProperty(symbol); } - // CommonsJS require/module/exports all have type any. + // CommonsJS require and module both have type any. if (symbol === requireSymbol || symbol === moduleSymbol) { return links.type = anyType; } @@ -30219,6 +30901,10 @@ var ts; return links.type = anyType; } // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } if (declaration.kind === 248 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } @@ -30239,7 +30925,7 @@ var ts; declaration.kind === 184 /* PropertyAccessExpression */ && declaration.parent.kind === 199 /* BinaryExpression */) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else if (ts.isJSDocPropertyTag(declaration) + else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) || ts.isIdentifier(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) @@ -30510,13 +31196,15 @@ var ts; case 152 /* MethodSignature */: case 162 /* FunctionType */: case 163 /* ConstructorType */: - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: case 233 /* FunctionDeclaration */: case 153 /* MethodDeclaration */: case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: case 236 /* TypeAliasDeclaration */: - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: case 176 /* MappedType */: case 170 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); @@ -30526,7 +31214,7 @@ var ts; else if (node.kind === 170 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 234 /* ClassDeclaration */ || node.kind === 204 /* ClassExpression */ || node.kind === 235 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; @@ -30545,13 +31233,12 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 235 /* InterfaceDeclaration */ || node.kind === 234 /* ClassDeclaration */ || - node.kind === 204 /* ClassExpression */ || node.kind === 236 /* TypeAliasDeclaration */) { + if (node.kind === 235 /* InterfaceDeclaration */ || + node.kind === 234 /* ClassDeclaration */ || + node.kind === 204 /* ClassExpression */ || + ts.isTypeAlias(node)) { var declaration = node; - var typeParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - if (typeParameters) { - result = appendTypeParameters(result, typeParameters); - } + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); } } return result; @@ -30828,9 +31515,9 @@ var ts; return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 292 /* JSDocTypedefTag */ || d.kind === 236 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 236 /* TypeAliasDeclaration */; }); - var typeNode = declaration.kind === 292 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { @@ -31035,7 +31722,7 @@ var ts; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && - (!typeParameters || typeParameters.every(isThislessTypeParameter)); + typeParameters.every(isThislessTypeParameter); } /** * Returns true if the class or interface member given by the symbol is free of "this" references. The @@ -31084,6 +31771,9 @@ var ts; var symbol = type.symbol; var members = getMembersOfSymbol(symbol); type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); @@ -31213,9 +31903,9 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_3 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); } lateSymbol.nameType = type; @@ -31644,10 +32334,8 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var constraintDeclaration = type.declaration.typeParameter.constraint; var include = keyofStringsOnly ? 32 /* StringLiteral */ : 1120 /* StringOrNumberLiteralOrUnique */; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; @@ -31720,15 +32408,21 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : unknownType); } + function getConstraintDeclarationForMappedType(type) { + return type.declaration.typeParameter.constraint; + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); + return constraintDeclaration.kind === 174 /* TypeOperator */ && + constraintDeclaration.operator === 128 /* KeyOfKeyword */; + } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); } else { // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, @@ -31889,9 +32583,9 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(type.checkType); + var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); if (constraint) { - var mapper = createTypeMapper([type.root.checkType], [constraint]); + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 16384 /* Never */)) { return instantiated; @@ -32278,9 +32972,10 @@ var ts; // type checking functions). function getTypeParametersFromDeclaration(declaration) { var result; - ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); - }); + } return result; } function symbolsToArray(symbols) { @@ -32295,10 +32990,10 @@ var ts; function isJSDocOptionalParameter(node) { return ts.isInJavaScriptFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 280 /* JSDocOptionalType */ + node.type && node.type.kind === 282 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 280 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -32310,7 +33005,7 @@ var ts; return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -32327,6 +33022,13 @@ var ts; } return false; } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */; + } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); @@ -32384,7 +33086,7 @@ var ts; for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); @@ -32415,6 +33117,7 @@ var ts; for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); @@ -32427,12 +33130,13 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 177 /* LiteralType */) { + if (type && type.kind === 177 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || isUntypedSignatureInJSFile || isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { @@ -32466,7 +33170,7 @@ var ts; * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` */ function maybeAddJsSyntheticRestParameter(declaration, parameters) { - if (!containsArgumentsReference(declaration)) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { return false; } var lastParam = ts.lastOrUndefined(declaration.parameters); @@ -32859,7 +33563,7 @@ var ts; var isJs = ts.isInJavaScriptFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 286 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && node.parent.kind !== 289 /* JSDocAugmentsTag */; var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -33010,7 +33714,7 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node)) { + while (node && !ts.isStatement(node) && node.kind !== 285 /* JSDocComment */) { var parent = node.parent; if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); @@ -33460,7 +34164,7 @@ var ts; includes & 4096 /* Undefined */ ? includes & 16777216 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 8374815 /* NotUnit */ ? 0 : 268435456 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -33497,7 +34201,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -33508,7 +34212,7 @@ var ts; var type = unionTypes.get(id); if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */); - type = createType(131072 /* Union */ | propagatedFlags); + type = createType(131072 /* Union */ | propagatedFlags | unionOfUnitTypes); unionTypes.set(id, type); type.types = types; /* @@ -33525,7 +34229,8 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -33574,6 +34279,31 @@ var ts; } } } + // When intersecting unions of unit types we can simply intersect based on type identity. + // Here we remove all unions of unit types from the given list and replace them with a + // a single union containing an intersection of the unit types. + function intersectUnionsOfUnitTypes(types) { + var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 268435456 /* UnionOfUnitTypes */) !== 0; }); + var unionType = types[unionIndex]; + var intersection = unionType.types; + var i = types.length - 1; + var _loop_5 = function () { + var t = types[i]; + if (t.flags & 268435456 /* UnionOfUnitTypes */) { + intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + ts.orderedRemoveItemAt(types, i); + } + i--; + }; + while (i > unionIndex) { + _loop_5(); + } + if (intersection === unionType.types) { + return false; + } + types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 268435456 /* UnionOfUnitTypes */); + return true; + } // We normalize combinations of intersection and union types based on the distributive property of the '&' // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection // types with union type constituents into equivalent union types with intersection type constituents and @@ -33608,6 +34338,12 @@ var ts; return typeSet[0]; } if (includes & 131072 /* Union */) { + if (includes & 268435456 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 131072 /* Union */) !== 0; }); @@ -33629,7 +34365,8 @@ var ts; function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -33806,6 +34543,10 @@ var ts; // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // the type itself if no transformation is possible. function getSimplifiedIndexedAccessType(type) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; var objectType = type.objectType; if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) { // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or @@ -33824,7 +34565,7 @@ var ts; regularTypes.push(t); } } - return getUnionType([ + return type.simplified = getUnionType([ getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), getIntersectionType(stringIndexTypes) ]); @@ -33835,7 +34576,7 @@ var ts; // eventually anyway, but it easier to reason about. if (ts.some(objectType.types, isMappedTypeToNever)) { var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); } } // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper @@ -33843,15 +34584,15 @@ var ts; // construct the type Box. We do not further simplify the result because mapped types can be recursive // and we might never terminate. if (isGenericMappedType(objectType)) { - return substituteIndexedMappedType(objectType, type); + return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { - return substituteIndexedMappedType(constraint, type); + return type.simplified = substituteIndexedMappedType(constraint, type); } } - return type; + return type.simplified = type; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); @@ -33916,7 +34657,7 @@ var ts; var type = createObjectType(32 /* Mapped */, node.symbol); type.declaration = node; type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); links.resolvedType = type; // Eagerly resolve the constraint type which forces an error if the constraint type circularly // references itself through one or more type aliases. @@ -33939,14 +34680,14 @@ var ts; var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */); var combinedMapper; if (root.inferTypeParameters) { - var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + var context_1 = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); if (!isDeferred) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); + inferTypes(context_1.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); } - combinedMapper = combineTypeMappers(mapper, context); + combinedMapper = combineTypeMappers(mapper, context_1); } if (!isDeferred) { // Return union of trueType and falseType for 'any' since it matches anything @@ -34017,7 +34758,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var checkType = getTypeFromTypeNode(node.checkType); - var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); var root = { @@ -34030,7 +34772,7 @@ var ts; inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, - aliasSymbol: getAliasSymbolForTypeNode(node), + aliasSymbol: aliasSymbol, aliasTypeArguments: aliasTypeArguments }; links.resolvedType = getConditionalType(root, /*mapper*/ undefined); @@ -34129,7 +34871,7 @@ var ts; else { var type = createObjectType(16 /* Anonymous */, node.symbol); type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { type = createArrayType(type); } @@ -34139,10 +34881,9 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 236 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); + function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } /** @@ -34321,8 +35062,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119 /* AnyKeyword */: - case 276 /* JSDocAllType */: - case 277 /* JSDocUnknownType */: + case 278 /* JSDocAllType */: + case 279 /* JSDocUnknownType */: return anyType; case 137 /* StringKeyword */: return stringType; @@ -34363,21 +35104,22 @@ var ts; return getTypeFromUnionTypeNode(node); case 169 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 278 /* JSDocNullableType */: + case 280 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 280 /* JSDocOptionalType */: + case 282 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); case 172 /* ParenthesizedType */: - case 279 /* JSDocNonNullableType */: - case 275 /* JSDocTypeExpression */: + case 281 /* JSDocNonNullableType */: + case 277 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); case 162 /* FunctionType */: case 163 /* ConstructorType */: case 165 /* TypeLiteral */: - case 284 /* JSDocTypeLiteral */: - case 281 /* JSDocFunctionType */: + case 286 /* JSDocTypeLiteral */: + case 283 /* JSDocFunctionType */: + case 287 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 174 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); @@ -34567,6 +35309,15 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; + if (ts.isInJavaScriptFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); if (isJavaScriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); @@ -34608,8 +35359,8 @@ var ts; // between the node and the type parameter declaration, if the node contains actual references to the // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_2 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_2; })) { + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_3; })) { return ts.forEachChild(node, containsReference); } } @@ -35459,7 +36210,7 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { + var _loop_6 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -35496,7 +36247,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_5(prop); + var state_3 = _loop_6(prop); if (typeof state_3 === "object") return state_3.value; } @@ -35802,16 +36553,19 @@ var ts; } } var constraint = getConstraintForRelation(source); - if (!constraint || constraint.flags & 1 /* Any */) { + if (!constraint || (source.flags & 32768 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~134217728 /* NonPrimitive */))) { errorInfo = saveErrorInfo; return result; } } - else if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var instantiated = getTypeWithThisArgument(constraint, source); + if (result = isRelatedTo(instantiated, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else if (source.flags & 524288 /* Index */) { @@ -35939,10 +36693,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_1; - if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -38049,7 +38803,7 @@ var ts; if (type.flags & 131072 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 268435456 /* UnionOfUnitTypes */); } return f(type) ? type : neverType; } @@ -39285,7 +40039,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 281 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 283 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -39721,7 +40475,7 @@ var ts; // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? - getTypeOfExpression(left, /*cache*/ true) : type; + getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; @@ -40000,8 +40754,18 @@ var ts; return unknownType; } } - if (context.typeArguments) { - signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); }); + var links = getNodeLinks(context); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(valueType); + var cachedResolved = links.resolvedSignatures.get(cacheKey); + if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { + signatures = cachedResolved; + } + else if (!cachedResolved) { + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); } return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); } @@ -40312,7 +41076,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 179 /* ObjectBindingPattern */ || contextualType.pattern.kind === 183 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node); + var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; @@ -40908,6 +41672,37 @@ var ts; } return undefined; } + function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { + var links = getNodeLinks(openingLikeElement); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(elementType); + if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { + return; + } + else if (links.resolvedSignatures.get(cacheKey)) { + return links.resolvedSignatures.get(cacheKey); + } + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(elementType, 0 /* Call */); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + if (reportErrors) { + error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); + } + return; + } + } + // Instantiate in context of source type + var results = instantiateJsxSignatures(openingLikeElement, signatures); + links.resolvedSignatures.set(cacheKey, results); + return results; + } /** * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. * For instance: @@ -40963,19 +41758,10 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(elementType, 1 /* Construct */); - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(elementType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); - return unknownType; - } + var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); + if (!ts.length(instantiatedSignatures)) { + return unknownType; } - // Instantiate in context of source type - var instantiatedSignatures = instantiateJsxSignatures(openingLikeElement, signatures); var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. @@ -41199,7 +41985,7 @@ var ts; // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span if (ts.length(openingLikeElement.attributes.properties)) { var reportedError = false; - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (ts.isJsxSpreadAttribute(prop)) return "continue"; var name = ts.idText(prop.name); @@ -41213,7 +41999,7 @@ var ts; }; for (var _b = 0, _c = openingLikeElement.attributes.properties; _b < _c.length; _b++) { var prop = _c[_b]; - _loop_6(prop); + _loop_7(prop); } if (reportedError) { return; @@ -42484,10 +43270,10 @@ var ts; var isDecorator = node.kind === 149 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; - if (!isDecorator && !isJsxOpeningOrSelfClosingElement) { + if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (isTaggedTemplate || node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -43012,28 +43798,6 @@ var ts; */ function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); - return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - } - /** - * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. - * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible - * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. - * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures - */ - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) - if (elementType.flags & 131072 /* Union */) { - var types = elementType.types; - var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); - } - return result; - } var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); @@ -43053,7 +43817,18 @@ var ts; case 256 /* JsxOpeningElement */: case 255 /* JsxSelfClosingElement */: // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; + var exprTypes = checkExpression(node.tagName); + return forEachType(exprTypes, function (exprType) { + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + if (sfcResult && sfcResult !== unknownSignature) { + return sfcResult; + } + var sigs = getInstantiatedJsxSignatures(node, exprType); + if (candidatesOutArray && ts.length(sigs)) { + candidatesOutArray.push.apply(candidatesOutArray, sigs); + } + return ts.length(sigs) ? sigs[0] : unknownSignature; + }) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -43251,8 +44026,8 @@ var ts; if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); - var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + var file_4 = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file_4, originalSymbol, /*dontResolveAlias*/ false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); @@ -43706,7 +44481,7 @@ var ts; checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); if (isTypeAny(type)) { return type; } @@ -43940,8 +44715,8 @@ var ts; } if (type.flags & 393216 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -45036,7 +45811,7 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (node.kind !== 159 /* IndexSignature */ && node.kind !== 281 /* JSDocFunctionType */) { + if (node.kind !== 159 /* IndexSignature */ && node.kind !== 283 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -45499,7 +46274,7 @@ var ts; n.parent.kind !== 234 /* ClassDeclaration */ && n.parent.kind !== 204 /* ClassExpression */ && n.flags & 4194304 /* Ambient */) { - if (!(flags & 2 /* Ambient */)) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported flags |= 1 /* Export */; } @@ -45769,8 +46544,9 @@ var ts; switch (d.kind) { case 235 /* InterfaceDeclaration */: case 236 /* TypeAliasDeclaration */: - // A jsdoc typedef is, by definition, a type alias - case 292 /* JSDocTypedefTag */: + // A jsdoc typedef and callback are, by definition, type aliases + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: return 2 /* ExportType */; case 238 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ @@ -45792,10 +46568,10 @@ var ts; case 242 /* ImportEqualsDeclaration */: case 245 /* NamespaceImport */: case 244 /* ImportClause */: - var result_2 = 0 /* None */; + var result_3 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; case 231 /* VariableDeclaration */: case 181 /* BindingElement */: case 233 /* FunctionDeclaration */: @@ -46239,7 +47015,7 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDocTypedefTag(node) { + function checkJSDocTypeAliasTag(node) { if (!node.typeExpression) { // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); @@ -46363,7 +47139,13 @@ var ts; } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. - if (potentiallyUnusedIdentifiers) { + if (produceDiagnostics) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } // TODO: GH#22580 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); potentiallyUnusedIdentifiers.push(node); @@ -46373,10 +47155,6 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 273 /* SourceFile */: - case 238 /* ModuleDeclaration */: - checkUnusedModuleMembers(node, addDiagnostic); - break; case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); @@ -46385,6 +47163,8 @@ var ts; case 235 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; + case 273 /* SourceFile */: + case 238 /* ModuleDeclaration */: case 212 /* Block */: case 240 /* CaseBlock */: case 219 /* ForStatement */: @@ -46417,33 +47197,6 @@ var ts; } } } - function checkUnusedLocalsAndParameters(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - node.locals.forEach(function (local) { - // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. - // If it's a type parameter merged with a parameter, check if the parameter-side is used. - if (local.flags & 262144 /* TypeParameter */ ? (local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : !local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148 /* Parameter */) { - var parameter = ts.getRootDeclaration(local.valueDeclaration); - var name = ts.getNameOfDeclaration(local.valueDeclaration); - if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } - } - else { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local), addDiagnostic); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { @@ -46453,10 +47206,8 @@ var ts; return; } } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); - } + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -46504,7 +47255,7 @@ var ts; // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304 /* Ambient */) && typeParameters && ts.last(getSymbolOfNode(node).declarations) === node) { + if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { @@ -46513,50 +47264,91 @@ var ts; } } } - function checkUnusedModuleMembers(node, addDiagnostic) { - if (!(node.flags & 4194304 /* Ambient */)) { - // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. - var unusedImports_1 = ts.createMap(); - node.locals.forEach(function (local) { - if (local.isReferenced || local.exportSymbol) - return; - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isAmbientModule(declaration)) - continue; - if (isImportedDeclaration(declaration)) { - var importClause = importClauseFromImported(declaration); - var key = String(getNodeId(importClause)); - var group_1 = unusedImports_1.get(key); - if (group_1) { - group_1[1].push(declaration); - } - else { - unusedImports_1.set(key, [importClause, [declaration]]); + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration)) + continue; + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + if (parameter) { + var name = ts.getNameOfDeclaration(local.valueDeclaration); + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { + addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); } } - }); - unusedImports_1.forEach(function (_a) { - var importClause = _a[0], unuseds = _a[1]; - var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { - for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { - var unused = unuseds_1[_i]; - errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); - } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } - else if (unuseds.length === 1) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else if (unuseds.length === 1) { + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); + } + else { + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } - else { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl))); - } - }); - } + } + else if (bindingElements.length === 1) { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + } + else { + addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + }); } function isImportedDeclaration(node) { return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */; @@ -47731,7 +48523,7 @@ var ts; var declaration = declarations_6[_i]; // If this declaration has too few or too many type parameters, we report an error var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); - var numTypeParameters = ts.length(sourceParameters); + var numTypeParameters = sourceParameters.length; if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; } @@ -47879,7 +48671,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -47898,7 +48690,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -48747,9 +49539,9 @@ var ts; } } // Checks for export * conflicts - var exports = getExportsOfModule(moduleSymbol); - if (exports) { - exports.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -48855,27 +49647,28 @@ var ts; return checkInferType(node); case 178 /* ImportType */: return checkImportType(node); - case 286 /* JSDocAugmentsTag */: + case 289 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 292 /* JSDocTypedefTag */: - return checkJSDocTypedefTag(node); - case 288 /* JSDocParameterTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 292 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: checkSignatureDeclaration(node); // falls through - case 279 /* JSDocNonNullableType */: - case 278 /* JSDocNullableType */: - case 276 /* JSDocAllType */: - case 277 /* JSDocUnknownType */: - case 284 /* JSDocTypeLiteral */: + case 281 /* JSDocNonNullableType */: + case 280 /* JSDocNullableType */: + case 278 /* JSDocAllType */: + case 279 /* JSDocUnknownType */: + case 286 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 275 /* JSDocTypeExpression */: + case 277 /* JSDocTypeExpression */: return checkSourceElement(node.type); case 175 /* IndexedAccessType */: return checkIndexedAccessType(node); @@ -48987,8 +49780,8 @@ var ts; var paramTag = parent.parent; if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. - var host_2 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_2) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + if (host_1) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -48996,7 +49789,7 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_2.parameters); + var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -49059,6 +49852,9 @@ var ts; return ts.Debug.assertNever(kind); } } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -49074,25 +49870,19 @@ var ts; ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); deferredNodes = []; - if (produceDiagnostics) { - ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName)); - allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []); - } ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { if (unusedIsError(kind)) { diagnostics.add(diag); } }); } deferredNodes = undefined; - seenPotentiallyUnusedIdentifiers.clear(); - potentiallyUnusedIdentifiers = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -49388,10 +50178,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 288 /* JSDocParameterTag */) { + if (entityName.parent.kind === 292 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 291 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 295 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -49931,6 +50721,7 @@ var ts; function isRequiredInitializedParameter(parameter) { return strictNullChecks && !isOptionalParameter(parameter) && + !ts.isJSDocParameterTag(parameter) && parameter.initializer && !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } @@ -50181,7 +50972,22 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, - getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); + var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 156 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 155 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 267 /* HeritageClause */; @@ -50217,8 +51023,8 @@ var ts; var decl = _a[_i]; // check meaning of the local symbol to see if declaration needs to be analyzed further if (decl.symbol && decl.symbol.flags & meaning) { - var file = ts.getSourceFileOfNode(decl); - var typeReferenceDirective = fileToDirective.get(file.path); + var file_5 = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file_5.path); if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } @@ -50253,8 +51059,8 @@ var ts; // check that at least one declaration of top level symbol originates from type declaration file for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var file = ts.getSourceFileOfNode(decl); - if (fileToDirective.has(file.path)) { + var file_6 = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file_6.path)) { return true; } } @@ -50272,25 +51078,25 @@ var ts; function initializeTypeChecker() { // Bind all source files and propagate errors for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - ts.bindSourceFile(file, compilerOptions); + var file_7 = _a[_i]; + ts.bindSourceFile(file_7, compilerOptions); } // Initialize global symbol table var augmentations; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { - var file = _c[_b]; - if (!ts.isExternalOrCommonJsModule(file)) { - mergeSymbolTable(globals, file.locals); + var file_8 = _c[_b]; + if (!ts.isExternalOrCommonJsModule(file_8)) { + mergeSymbolTable(globals, file_8.locals); } - if (file.patternAmbientModules && file.patternAmbientModules.length) { - patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + if (file_8.patternAmbientModules && file_8.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file_8.patternAmbientModules); } - if (file.moduleAugmentations.length) { - (augmentations || (augmentations = [])).push(file.moduleAugmentations); + if (file_8.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file_8.moduleAugmentations); } - if (file.symbol && file.symbol.globalExports) { + if (file_8.symbol && file_8.symbol.globalExports) { // Merge in UMD exports with first-in-wins semantics (see #9771) - var source = file.symbol.globalExports; + var source = file_8.symbol.globalExports; source.forEach(function (sourceSymbol, id) { if (!globals.has(id)) { globals.set(id, sourceSymbol); @@ -50742,7 +51548,7 @@ var ts; } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(ts.getEffectiveTypeParameterDeclarations(node), file); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { if (!ts.isArrowFunction(node)) { @@ -51427,8 +52233,8 @@ var ts; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + if (ts.isNodeArray(typeParameters)) { + var pos = typeParameters.pos, end = typeParameters.end; return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } @@ -51578,7 +52384,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -51657,10 +52463,8 @@ var ts; if (!elements || elements === ts.emptyArray) { elements = []; } - else { - if (ts.isNodeArray(elements)) { - return elements; - } + else if (ts.isNodeArray(elements)) { + return elements; } var array = elements; array.pos = -1; @@ -51720,6 +52524,13 @@ var ts; node.text = text; return node; } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; function createLiteralFromNode(sourceNode) { var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; @@ -51753,7 +52564,7 @@ var ts; recordTempVariable(name); } if (reservedInNestedScopes) { - name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; } return name; } @@ -51779,7 +52590,7 @@ var ts; /** Create a unique name based on the supplied text. */ function createOptimisticUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateFlags = 3 /* Unique */ | 32 /* Optimistic */; + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -51788,18 +52599,15 @@ var ts; /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ function createFileLevelUniqueName(text) { var name = createOptimisticUniqueName(text); - name.autoGenerateFlags |= 64 /* FileLevel */; + name.autoGenerateFlags |= 32 /* FileLevel */; return name; } ts.createFileLevelUniqueName = createFileLevelUniqueName; - function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { - var name = createIdentifier(""); - name.autoGenerateFlags = 4 /* Node */; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; name.autoGenerateId = nextAutoGenerateId; name.original = node; - if (shouldSkipNameGenerationScope) { - name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; - } nextAutoGenerateId++; return name; } @@ -51890,7 +52698,7 @@ var ts; ts.updateQualifiedName = updateQualifiedName; function parenthesizeForComputedName(expression) { return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) || - expression.kind === 297 /* CommaListExpression */ ? + expression.kind === 301 /* CommaListExpression */ ? createParen(expression) : expression; } @@ -52940,6 +53748,13 @@ var ts; return block; } ts.createBlock = createBlock; + /* @internal */ + function createExpressionStatement(expression) { + var node = createSynthesizedNode(215 /* ExpressionStatement */); + node.expression = expression; + return node; + } + ts.createExpressionStatement = createExpressionStatement; function updateBlock(node, statements) { return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) @@ -52966,9 +53781,7 @@ var ts; } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(215 /* ExpressionStatement */); - node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); - return node; + return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression)); } ts.createStatement = createStatement; function updateStatement(node, expression) { @@ -53864,7 +54677,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295 /* NotEmittedStatement */); + var node = createSynthesizedNode(299 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -53876,7 +54689,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(303 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -53888,7 +54701,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(302 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -53903,7 +54716,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(300 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -53919,7 +54732,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297 /* CommaListExpression */) { + if (node.kind === 301 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -53929,7 +54742,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297 /* CommaListExpression */); + var node = createSynthesizedNode(301 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -53940,15 +54753,31 @@ var ts; : node; } ts.updateCommaList = updateCommaList; - function createBundle(sourceFiles) { + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } var node = ts.createNode(274 /* Bundle */); + node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; - function updateBundle(node, sourceFiles) { - if (node.sourceFiles !== sourceFiles) { - return createBundle(sourceFiles); + function createUnparsedSourceFile(text) { + var node = ts.createNode(275 /* UnparsedSource */); + node.text = text; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration) { + var node = ts.createNode(276 /* InputFiles */); + node.javascriptText = javascript; + node.declarationText = declaration; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); } return node; } @@ -54220,6 +55049,15 @@ var ts; return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); } ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; /** * Gets the constant value to emit for an expression. */ @@ -55192,7 +56030,7 @@ var ts; // if should be wrapped in parens since comma operator has the lowest precedence var emittedExpression = ts.skipPartiallyEmittedExpressions(e); return emittedExpression.kind === 199 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || - emittedExpression.kind === 297 /* CommaListExpression */ + emittedExpression.kind === 301 /* CommaListExpression */ ? ts.createParen(e) : e; } @@ -55212,7 +56050,7 @@ var ts; var check = ts.skipPartiallyEmittedExpressions(e); return (check.kind === 204 /* ClassExpression */ || check.kind === 191 /* FunctionExpression */ || - check.kind === 297 /* CommaListExpression */ || + check.kind === 301 /* CommaListExpression */ || ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */) ? ts.createParen(e) : e; @@ -55333,6 +56171,7 @@ var ts; switch (member.kind) { case 164 /* TypeQuery */: case 174 /* TypeOperator */: + case 171 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -55376,7 +56215,7 @@ var ts; case 184 /* PropertyAccessExpression */: node = node.expression; continue; - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -55406,7 +56245,7 @@ var ts; case 207 /* AsExpression */: case 208 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -55443,7 +56282,7 @@ var ts; case 189 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 207 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 208 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 300 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -55931,7 +56770,7 @@ var ts; statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements); } var declarations = context.endLexicalEnvironment(); - return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); } ts.visitLexicalEnvironment = visitLexicalEnvironment; /** @@ -56228,9 +57067,9 @@ var ts; case 273 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -56286,7 +57125,7 @@ var ts; case 214 /* EmptyStatement */: case 205 /* OmittedExpression */: case 230 /* DebuggerStatement */: - case 295 /* NotEmittedStatement */: + case 299 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -56665,10 +57504,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 300 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 297 /* CommaListExpression */: + case 301 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -56682,8 +57521,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements) - : ts.addRange(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + : ts.prependRange(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -56833,16 +57672,6 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; - function getNamedImportCount(node) { - if (!(node.importClause && node.importClause.namedBindings)) - return 0; - var names = node.importClause.namedBindings; - if (!names) - return 0; - if (!ts.isNamedImports(names)) - return 0; - return names.elements.length; - } function containsDefaultReference(node) { if (!node) return false; @@ -56853,12 +57682,40 @@ var ts; function isNamedDefaultReference(e) { return e.propertyName && e.propertyName.escapedText === "default" /* Default */; } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 273 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; function getImportNeedsImportStarHelper(node) { - return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); } ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { - return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -57595,7 +58452,21 @@ var ts; * at the next execution site, in document order */ var pendingExpressions; - return transformSourceFile; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 274 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText); + } + return prepend; + })); + } /** * Transform TypeScript-specific syntax in a SourceFile. * @@ -58085,7 +58956,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, context.endLexicalEnvironment()); + ts.prependRange(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -58290,7 +59161,7 @@ var ts; // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); var alias = ts.getSynthesizedClone(temp); - alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent @@ -58567,7 +59438,7 @@ var ts; function transformInitializedProperty(property, receiver) { // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) - ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */))) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); @@ -59597,6 +60468,11 @@ var ts; // we can safely elide the parentheses here, as a new synthetic // ParenthesizedExpression will be inserted if we remove parentheses too // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } return ts.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -59702,8 +60578,9 @@ var ts; currentNamespaceContainerName = localName; var statements = []; startLexicalEnvironment(); - ts.addRange(statements, ts.map(node.members, transformEnumMember)); - ts.addRange(statements, endLexicalEnvironment()); + var members = ts.map(node.members, transformEnumMember); + ts.prependRange(statements, endLexicalEnvironment()); + ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); @@ -59943,7 +60820,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -60480,7 +61357,7 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -60752,7 +61629,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -60774,7 +61651,7 @@ var ts; var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); } else { result = expression; @@ -60964,7 +61841,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -61042,9 +61919,14 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -61346,7 +62228,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -61371,11 +62253,11 @@ var ts; statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); } ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); - var trailingStatements = endLexicalEnvironment(); - if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) { + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.prependRange(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); - ts.addRange(statements, trailingStatements); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } return body; @@ -61533,7 +62415,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -61550,7 +62432,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };" + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -61561,7 +62443,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };" + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -61575,7 +62457,7 @@ var ts; function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transform JSX-specific syntax in a SourceFile. * @@ -62083,7 +62965,7 @@ var ts; (function (ts) { function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -62291,7 +63173,7 @@ var ts; * be reset. */ var enabledSubstitutions; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -62467,7 +63349,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -62721,7 +63603,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -62834,7 +63716,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -63469,6 +64351,7 @@ var ts; var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression); ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); statements.push(returnStatement); // To align with the source map emit for the old emitter, we set a custom @@ -63476,7 +64359,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); + ts.prependRange(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { @@ -64057,7 +64940,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.addRange(statements_4, lexicalEnvironment); + ts.prependRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -64510,10 +65393,12 @@ var ts; // We skip any outer expressions in a number of places to get to the innermost // expression, but we will restore them later to preserve comments and source maps. var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); - // The class statements are the statements generated by visiting the first statement of the + // The class statements are the statements generated by visiting the first statement with initializer of the // body (1), while all other statements are added to remainingStatements (2) - var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); - var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); // We know there is only one variable declaration here as we verified this in an // earlier call to isTypeScriptClassWrapper @@ -64523,6 +65408,7 @@ var ts; // we see as an assignment, for example: // // (function () { + // var C_1; // var C = C_1 = (function () { // function C() { // } @@ -64531,7 +65417,6 @@ var ts; // }()); // C = C_1 = __decorate([dec], C); // return C; - // var C_1; // }()) // var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); @@ -65161,7 +66046,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.enableSubstitution(184 /* PropertyAccessExpression */); context.enableSubstitution(269 /* PropertyAssignment */); - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. * @@ -65473,7 +66358,7 @@ var ts; var exceptionBlockStack; // A stack of containing exception blocks. var currentExceptionBlock; // The current exception block. var withBlockStack; // A stack containing `with` blocks. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; @@ -65730,7 +66615,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -67923,7 +68808,7 @@ var ts; var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -67966,7 +68851,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -68189,7 +69074,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -68211,7 +69096,7 @@ var ts; */ function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); if (expressionResult) { if (emitAsReturn) { var statement = ts.createReturn(expressionResult); @@ -68252,29 +69137,84 @@ var ts; return visitFunctionDeclaration(node); case 234 /* ClassDeclaration */: return visitClassDeclaration(node); - case 298 /* MergeDeclarationMarker */: + case 302 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 303 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } - function importCallExpressionVisitor(node) { - // This visitor does not need to descend into the tree if there is no dynamic import, + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } else { - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 269 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 270 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 271 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 153 /* MethodDeclaration */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } function visitImportCallExpression(node) { - var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: @@ -68568,10 +69508,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -68585,13 +69525,13 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), - /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), /*location*/ node), /*original*/ node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -68613,10 +69553,10 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -68661,7 +69601,7 @@ var ts; } } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -68673,6 +69613,21 @@ var ts; } return ts.singleOrMany(statements); } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } /** * Transforms an exported variable with an initializer into an expression. * @@ -68680,13 +69635,13 @@ var ts; */ function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), /*visitor*/ undefined, context, 0 /* All */, - /*needsValue*/ false, createExportExpression); + /*needsValue*/ false, createAllExportExpressions); } else { return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), - /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); } } /** @@ -69090,8 +70045,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { - var exportName = exportedNames_1[_i]; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression, /*location*/ node); @@ -69127,8 +70082,8 @@ var ts; ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; - for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { - var exportName = exportedNames_2[_i]; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); @@ -69215,7 +70170,7 @@ var ts; var hoistedStatements; var enclosingBlockScopedContainer; var noSubstitution; // Set of nodes for which substitution rules should be ignored. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -69388,7 +70343,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addRange(statements, endLexicalEnvironment()); + ts.prependRange(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -69518,12 +70473,12 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_2 = dependencyGroups_1[_i]; + var group_1 = dependencyGroups_1[_i]; // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { @@ -70116,9 +71071,9 @@ var ts; return visitCatchClause(node); case 212 /* Block */: return visitBlock(node); - case 298 /* MergeDeclarationMarker */: + case 302 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 303 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -70551,8 +71506,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { - var exportName = exportedNames_3[_i]; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } return expression; @@ -70585,8 +71540,8 @@ var ts; var expression = node.kind === 198 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; - for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { - var exportName = exportedNames_4[_i]; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } if (node.kind === 198 /* PostfixUnaryExpression */) { @@ -70653,7 +71608,7 @@ var ts; context.enableEmitNotification(273 /* SourceFile */); context.enableSubstitution(71 /* Identifier */); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -71160,7 +72115,12 @@ var ts; return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */; /** * Transforms a ts file into a .d.ts file * This process requires type information, which is retrieved through the emit resolver. Because of this, @@ -71180,19 +72140,22 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, reportInaccessibleThisError: reportInaccessibleThisError, reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, - reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, }; var errorNameNode; var currentSourceFile; + var refs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); var noResolve = options.noResolve, stripInternal = options.stripInternal; - var host = context.getEmitHost(); return transformRoot; function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { if (!typeReferenceDirectives) { @@ -71204,6 +72167,10 @@ var ts; necessaryTypeRefernces.set(ref, true); } } + function trackReferencedAmbientModule(node) { + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } function handleSymbolAccessibilityError(symbolAccessibilityResult) { if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info @@ -71234,6 +72201,8 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } @@ -71277,12 +72246,16 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); return newFile; } needsDeclare = true; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - return ts.updateSourceFileNode(sourceFile, filterCandidateImports(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 276 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText); + } })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); @@ -71305,13 +72278,13 @@ var ts; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); necessaryTypeRefernces = undefined; - var refs = collectReferences(currentSourceFile, ts.createMap()); + refs = collectReferences(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); - refs.forEach(referenceVisitor); var statements = ts.visitNodes(node.statements, visitDeclarationStatements); - var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); @@ -71323,17 +72296,19 @@ var ts; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports - for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { - var importStatement = emittedImports_1[_i]; - if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { - var expr = importStatement.moduleReference.expression; - if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { return undefined; } } - else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { - return undefined; - } } return { fileName: typeName, pos: -1, end: -1 }; } @@ -71366,7 +72341,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); if (elem) { - ret.set("" + ts.getNodeId(elem), elem); + ret.set("" + ts.getOriginalNodeId(elem), elem); } }); return ret; @@ -71583,7 +72558,7 @@ var ts; } // Nothing visible } - function filterCandidateImports(statements) { + function transformAndReplaceLatePaintedStatements(statements) { // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during // error handling which must now be included in the output and themselves checked for errors. // For example: @@ -71598,62 +72573,45 @@ var ts; // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. - var unconsideredStatements = []; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); - if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope - unconsideredStatements.push(i); - continue; - } if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was foudn which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); - } - switch (i.kind) { - case 242 /* ImportEqualsDeclaration */: { - var result = transformImportEqualsDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 243 /* ImportDeclaration */: { - var result = transformImportDeclaration(i); - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - case 213 /* VariableStatement */: { - var result = transformVariableStatement(i, /*privateDeclaration*/ true); // Transform the statement (potentially again, possibly revealing more sub-nodes) - lateStatementReplacementMap.set("" + ts.getNodeId(i), result); - break; - } - default: ts.Debug.assertNever(i, "Unhandled late painted statement!"); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } - // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not - // be considered in the child scope - lateMarkedStatements = unconsideredStatements; // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list // (and remove them from the set to examine for outter declarations) return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); - } - function visitLateVisibilityMarkedStatements(statement) { - if (ts.isLateVisibilityPaintedStatement(statement)) { - var key = "" + ts.getNodeId(statement); - if (lateStatementReplacementMap.has(key)) { - var result = lateStatementReplacementMap.get(key); - lateStatementReplacementMap.delete(key); - if (result && ts.isSourceFile(statement.parent) && !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */)) { - // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier - needsScopeFixMarker = true; + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; } - return result; } - else { - return ts.getParseTreeNode(statement) ? undefined : statement; - } - } - else { return statement; } } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } function visitDeclarationSubtree(input) { if (shouldStripInternal(input)) return; @@ -71851,13 +72809,21 @@ var ts; return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } } - case 242 /* ImportEqualsDeclaration */: + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 242 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } case 243 /* ImportDeclaration */: { - // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later - // to reduce the likelihood we need to rewrite it - lateMarkedStatements = lateMarkedStatements || []; - ts.pushIfUnique(lateMarkedStatements, input); - return input; + return transformImportDeclaration(input); } } if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) @@ -71870,52 +72836,53 @@ var ts; previousEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = input; } - var previousNeedsDeclare; var canProdiceDiagnostic = ts.canProduceDiagnostics(input); var oldDiag = getSymbolAccessibilityDiagnostic; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); } - var oldPossibleImports; + var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 236 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(ts.updateTypeAliasDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 235 /* InterfaceDeclaration */: { return cleanup(ts.updateInterfaceDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 233 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type return cleanup(ts.updateFunctionDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), + /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); } case 238 /* ModuleDeclaration */: { - previousNeedsDeclare = needsDeclare; needsDeclare = false; - oldPossibleImports = lateMarkedStatements; - lateMarkedStatements = undefined; var inner = input.body; if (inner && inner.kind === 239 /* ModuleBlock */) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); - var body = ts.updateModuleBlock(inner, filterCandidateImports(statements)); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); return cleanup(ts.updateModuleDeclaration(input, /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; - var mods = ensureModifiers(input); + var mods = ensureModifiers(input, isPrivate); needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); return cleanup(ts.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements))); + /*decorators*/ undefined, mods, input.name, body)); } } case 234 /* ClassDeclaration */: { - var modifiers = ts.createNodeArray(ensureModifiers(input)); + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); var parameterProperties = void 0; @@ -71985,12 +72952,10 @@ var ts; } } case 213 /* VariableStatement */: { - var result = transformVariableStatement(input); - lateStatementReplacementMap.set("" + ts.getNodeId(input), result); // Don't actually elide yet; just leave as original node - will be elided/swapped by late pass - return cleanup(input); + return cleanup(transformVariableStatement(input, isPrivate)); } case 237 /* EnumDeclaration */: { - return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; // Rewrite enum values to their constants, if available @@ -72001,27 +72966,20 @@ var ts; } // Anything left unhandled is an error, so this should be unreachable return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); - function cleanup(returnValue) { + function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; } - if (input.kind === 238 /* ModuleDeclaration */) { - needsDeclare = previousNeedsDeclare; - lateMarkedStatements = ts.concatenate(oldPossibleImports, lateMarkedStatements); - } if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (returnValue && (!ts.isLateVisibilityPaintedStatement(input) || lateStatementReplacementMap.get("" + ts.getNodeId(input)))) { - if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) { - // Exported top-level member indicates moduleness - resultHasExternalModuleIndicator = true; - } + if (input.kind === 238 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; } - if (returnValue === input) { - return returnValue; + if (node === input) { + return node; } - return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } function transformVariableStatement(input, privateDeclaration) { @@ -72098,7 +73056,7 @@ var ts; return maskModifierFlags(node, mask, additions); } function ensureAccessor(node) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + var accessors = resolver.getAllAccessorDeclarations(node); if (node.kind !== accessors.firstAccessor.kind) { return; } @@ -72111,7 +73069,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -72125,7 +73083,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -72287,7 +73245,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(300 /* Count */); + var enabledSyntaxKindFeatures = new Array(304 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -72782,7 +73740,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 295 /* NotEmittedStatement */ + if (node.kind !== 299 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -72799,7 +73757,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 295 /* NotEmittedStatement */ + if (node.kind !== 299 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -72975,7 +73933,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 299 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -73299,6 +74257,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); /*@internal*/ /** @@ -73315,7 +74274,7 @@ var ts; var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var bundle = ts.createBundle(sourceFiles); + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; @@ -73341,7 +74300,8 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); @@ -73350,17 +74310,27 @@ var ts; var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath }; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; + } // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } if (options.jsx === 1 /* Preserve */) { if (ts.isSourceFileJavaScript(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { @@ -73374,9 +74344,10 @@ var ts; } return ".js" /* Js */; } + ts.getOutputExtension = getOutputExtension; /*@internal*/ // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; @@ -73390,6 +74361,7 @@ var ts; mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, }); + var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; // Emit each output file ts.performance.mark("beforePrint"); @@ -73402,8 +74374,8 @@ var ts; sourceMaps: sourceMapDataList }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -73415,10 +74387,12 @@ var ts; if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } } - function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { - var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { // Make sure not to write js file and source map file if any of them cannot be written if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { emitSkipped = true; @@ -73428,7 +74402,7 @@ var ts; return; } // Transform the source files - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false); + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); // Create a printer to print the nodes var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { // resolver hooks @@ -73443,7 +74417,8 @@ var ts; // emitter hooks onSetSourceFile: setSourceFile, }); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); // Clean up emit nodes on parse tree transform.dispose(); } @@ -73454,8 +74429,8 @@ var ts; var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); - var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles; - var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); if (ts.length(declarationTransform.diagnostics)) { for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { var diagnostic = _b[_a]; @@ -73477,17 +74452,18 @@ var ts; var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap); + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); } declarationTransform.dispose(); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { var bundle = sourceFileOrBundle.kind === 274 /* Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 273 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { - printer.writeBundle(bundle, writer); + printer.writeBundle(bundle, writer, bundleInfo); } else { printer.writeFile(sourceFile, writer); @@ -73503,9 +74479,15 @@ var ts; } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } // Reset state mapRecorder.reset(); writer.clear(); + bundleInfo = createDefaultBundleInfo(); } function setSourceFile(node) { sourceMap.setSourceFile(node); @@ -73515,6 +74497,13 @@ var ts; } } ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } @@ -73572,6 +74561,7 @@ var ts; switch (node.kind) { case 273 /* SourceFile */: return printFile(node); case 274 /* Bundle */: return printBundle(node); + case 275 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -73588,6 +74578,10 @@ var ts; writeFile(sourceFile, beginPrint()); return endPrint(); } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; setWriter(output); @@ -73605,7 +74599,7 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output) { + function writeBundle(bundle, output, bundleInfo) { isOwnFileEmit = false; var previousWriter = writer; setWriter(output); @@ -73613,13 +74607,28 @@ var ts; emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); - for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { - var sourceFile = _b[_a]; + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + writeLine(); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; print(0 /* SourceFile */, sourceFile, sourceFile); } reset(); writer = previousWriter; } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } function writeFile(sourceFile, output) { isOwnFileEmit = true; var previousWriter = writer; @@ -73642,7 +74651,8 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmitWithNotification(hint, node); + var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -73665,417 +74675,422 @@ var ts; comments.reset(); setWriter(/*output*/ undefined); } - // TODO: Should this just be `emit`? - // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034 - function emitIfPresent(node) { - if (node) { - emit(node); - } - } function emit(node) { - pipelineEmitWithNotification(4 /* Unspecified */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - pipelineEmitWithNotification(2 /* IdentifierName */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - pipelineEmitWithNotification(1 /* Expression */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, hint) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Comments */: + if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + return pipelineEmitWithComments; + } + return pipelineEmitWithoutComments; + case 2 /* SourceMaps */: + if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { + return pipelineEmitWithSourceMap; + } + // falls through + case 3 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + } + } + function getNextPipelinePhase(currentPhase, hint) { + return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - if (onEmitNode) { - onEmitNode(hint, node, pipelineEmitWithComments); - } - else { - pipelineEmitWithComments(hint, node); - } + ts.Debug.assertDefined(onEmitNode); + onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); } function pipelineEmitWithComments(hint, node) { - node = trySubstituteNode(hint, node); - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { - emitNodeWithComments(hint, node, pipelineEmitWithSourceMap); - } - else { - pipelineEmitWithSourceMap(hint, node); - } + ts.Debug.assertDefined(emitNodeWithComments); + ts.Debug.assert(hint !== 0 /* SourceFile */); + emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); + } + function pipelineEmitWithoutComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); + pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); - } - else { - pipelineEmitWithHint(hint, node); - } + ts.Debug.assertDefined(onEmitSourceMapOfNode); + ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */); + onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { - switch (hint) { - case 0 /* SourceFile */: return pipelineEmitSourceFile(node); - case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node); - case 1 /* Expression */: return pipelineEmitExpression(node); - case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 4 /* Unspecified */: return pipelineEmitUnspecified(node); + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + return emitLiteral(node); + case 275 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 145 /* QualifiedName */: + return emitQualifiedName(node); + case 146 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 147 /* TypeParameter */: + return emitTypeParameter(node); + case 148 /* Parameter */: + return emitParameter(node); + case 149 /* Decorator */: + return emitDecorator(node); + // Type members + case 150 /* PropertySignature */: + return emitPropertySignature(node); + case 151 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 152 /* MethodSignature */: + return emitMethodSignature(node); + case 153 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 154 /* Constructor */: + return emitConstructor(node); + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 157 /* CallSignature */: + return emitCallSignature(node); + case 158 /* ConstructSignature */: + return emitConstructSignature(node); + case 159 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 160 /* TypePredicate */: + return emitTypePredicate(node); + case 161 /* TypeReference */: + return emitTypeReference(node); + case 162 /* FunctionType */: + return emitFunctionType(node); + case 283 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 163 /* ConstructorType */: + return emitConstructorType(node); + case 164 /* TypeQuery */: + return emitTypeQuery(node); + case 165 /* TypeLiteral */: + return emitTypeLiteral(node); + case 166 /* ArrayType */: + return emitArrayType(node); + case 167 /* TupleType */: + return emitTupleType(node); + case 168 /* UnionType */: + return emitUnionType(node); + case 169 /* IntersectionType */: + return emitIntersectionType(node); + case 170 /* ConditionalType */: + return emitConditionalType(node); + case 171 /* InferType */: + return emitInferType(node); + case 172 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 206 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 173 /* ThisType */: + return emitThisType(); + case 174 /* TypeOperator */: + return emitTypeOperator(node); + case 175 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 176 /* MappedType */: + return emitMappedType(node); + case 177 /* LiteralType */: + return emitLiteralType(node); + case 178 /* ImportType */: + return emitImportTypeNode(node); + case 278 /* JSDocAllType */: + write("*"); + return; + case 279 /* JSDocUnknownType */: + write("?"); + return; + case 280 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 281 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 282 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 284 /* JSDocVariadicType */: + return emitJSDocVariadicType(node); + // Binding patterns + case 179 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 180 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 181 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 210 /* TemplateSpan */: + return emitTemplateSpan(node); + case 211 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 212 /* Block */: + return emitBlock(node); + case 213 /* VariableStatement */: + return emitVariableStatement(node); + case 214 /* EmptyStatement */: + return emitEmptyStatement(); + case 215 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 216 /* IfStatement */: + return emitIfStatement(node); + case 217 /* DoStatement */: + return emitDoStatement(node); + case 218 /* WhileStatement */: + return emitWhileStatement(node); + case 219 /* ForStatement */: + return emitForStatement(node); + case 220 /* ForInStatement */: + return emitForInStatement(node); + case 221 /* ForOfStatement */: + return emitForOfStatement(node); + case 222 /* ContinueStatement */: + return emitContinueStatement(node); + case 223 /* BreakStatement */: + return emitBreakStatement(node); + case 224 /* ReturnStatement */: + return emitReturnStatement(node); + case 225 /* WithStatement */: + return emitWithStatement(node); + case 226 /* SwitchStatement */: + return emitSwitchStatement(node); + case 227 /* LabeledStatement */: + return emitLabeledStatement(node); + case 228 /* ThrowStatement */: + return emitThrowStatement(node); + case 229 /* TryStatement */: + return emitTryStatement(node); + case 230 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 231 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 232 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 233 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 234 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 235 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 236 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 237 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 238 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 239 /* ModuleBlock */: + return emitModuleBlock(node); + case 240 /* CaseBlock */: + return emitCaseBlock(node); + case 241 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 242 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 243 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 244 /* ImportClause */: + return emitImportClause(node); + case 245 /* NamespaceImport */: + return emitNamespaceImport(node); + case 246 /* NamedImports */: + return emitNamedImports(node); + case 247 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 248 /* ExportAssignment */: + return emitExportAssignment(node); + case 249 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 250 /* NamedExports */: + return emitNamedExports(node); + case 251 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 252 /* MissingDeclaration */: + return; + // Module references + case 253 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 10 /* JsxText */: + return emitJsxText(node); + case 256 /* JsxOpeningElement */: + case 259 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 257 /* JsxClosingElement */: + case 260 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 261 /* JsxAttribute */: + return emitJsxAttribute(node); + case 262 /* JsxAttributes */: + return emitJsxAttributes(node); + case 263 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 264 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 265 /* CaseClause */: + return emitCaseClause(node); + case 266 /* DefaultClause */: + return emitDefaultClause(node); + case 267 /* HeritageClause */: + return emitHeritageClause(node); + case 268 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 269 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 270 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 271 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 272 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (ignored) + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + node = trySubstituteNode(1 /* Expression */, node); + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + return emitNumericLiteral(node); + case 9 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 97 /* SuperKeyword */: + case 101 /* TrueKeyword */: + case 99 /* ThisKeyword */: + case 91 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 182 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 183 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 184 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 185 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 186 /* CallExpression */: + return emitCallExpression(node); + case 187 /* NewExpression */: + return emitNewExpression(node); + case 188 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 189 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 190 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 191 /* FunctionExpression */: + return emitFunctionExpression(node); + case 192 /* ArrowFunction */: + return emitArrowFunction(node); + case 193 /* DeleteExpression */: + return emitDeleteExpression(node); + case 194 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 195 /* VoidExpression */: + return emitVoidExpression(node); + case 196 /* AwaitExpression */: + return emitAwaitExpression(node); + case 197 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 198 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 199 /* BinaryExpression */: + return emitBinaryExpression(node); + case 200 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 201 /* TemplateExpression */: + return emitTemplateExpression(node); + case 202 /* YieldExpression */: + return emitYieldExpression(node); + case 203 /* SpreadElement */: + return emitSpreadExpression(node); + case 204 /* ClassExpression */: + return emitClassExpression(node); + case 205 /* OmittedExpression */: + return; + case 207 /* AsExpression */: + return emitAsExpression(node); + case 208 /* NonNullExpression */: + return emitNonNullExpression(node); + case 209 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 254 /* JsxElement */: + return emitJsxElement(node); + case 255 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 258 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 300 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 301 /* CommaListExpression */: + return emitCommaList(node); + } } - } - function pipelineEmitSourceFile(node) { - ts.Debug.assertNode(node, ts.isSourceFile); - emitSourceFile(node); - } - function pipelineEmitIdentifierName(node) { - ts.Debug.assertNode(node, ts.isIdentifier); - emitIdentifier(node); } function emitMappedTypeParameter(node) { emit(node.name); writeSpace(); writeKeyword("in"); writeSpace(); - emitIfPresent(node.constraint); - } - function pipelineEmitUnspecified(node) { - var kind = node.kind; - // Reserved words - // Strict mode reserved words - // Contextual keywords - if (ts.isKeyword(kind)) { - writeTokenNode(node, writeKeyword); - return; - } - switch (kind) { - // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Parse tree nodes - // Names - case 145 /* QualifiedName */: - return emitQualifiedName(node); - case 146 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 147 /* TypeParameter */: - return emitTypeParameter(node); - case 148 /* Parameter */: - return emitParameter(node); - case 149 /* Decorator */: - return emitDecorator(node); - // Type members - case 150 /* PropertySignature */: - return emitPropertySignature(node); - case 151 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 152 /* MethodSignature */: - return emitMethodSignature(node); - case 153 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 154 /* Constructor */: - return emitConstructor(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 157 /* CallSignature */: - return emitCallSignature(node); - case 158 /* ConstructSignature */: - return emitConstructSignature(node); - case 159 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 160 /* TypePredicate */: - return emitTypePredicate(node); - case 161 /* TypeReference */: - return emitTypeReference(node); - case 162 /* FunctionType */: - return emitFunctionType(node); - case 281 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 163 /* ConstructorType */: - return emitConstructorType(node); - case 164 /* TypeQuery */: - return emitTypeQuery(node); - case 165 /* TypeLiteral */: - return emitTypeLiteral(node); - case 166 /* ArrayType */: - return emitArrayType(node); - case 167 /* TupleType */: - return emitTupleType(node); - case 168 /* UnionType */: - return emitUnionType(node); - case 169 /* IntersectionType */: - return emitIntersectionType(node); - case 170 /* ConditionalType */: - return emitConditionalType(node); - case 171 /* InferType */: - return emitInferType(node); - case 172 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 206 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 173 /* ThisType */: - return emitThisType(); - case 174 /* TypeOperator */: - return emitTypeOperator(node); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 176 /* MappedType */: - return emitMappedType(node); - case 177 /* LiteralType */: - return emitLiteralType(node); - case 178 /* ImportType */: - return emitImportTypeNode(node); - case 276 /* JSDocAllType */: - write("*"); - return; - case 277 /* JSDocUnknownType */: - write("?"); - return; - case 278 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 279 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 280 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 282 /* JSDocVariadicType */: - return emitJSDocVariadicType(node); - // Binding patterns - case 179 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 180 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 181 /* BindingElement */: - return emitBindingElement(node); - // Misc - case 210 /* TemplateSpan */: - return emitTemplateSpan(node); - case 211 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Statements - case 212 /* Block */: - return emitBlock(node); - case 213 /* VariableStatement */: - return emitVariableStatement(node); - case 214 /* EmptyStatement */: - return emitEmptyStatement(); - case 215 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 216 /* IfStatement */: - return emitIfStatement(node); - case 217 /* DoStatement */: - return emitDoStatement(node); - case 218 /* WhileStatement */: - return emitWhileStatement(node); - case 219 /* ForStatement */: - return emitForStatement(node); - case 220 /* ForInStatement */: - return emitForInStatement(node); - case 221 /* ForOfStatement */: - return emitForOfStatement(node); - case 222 /* ContinueStatement */: - return emitContinueStatement(node); - case 223 /* BreakStatement */: - return emitBreakStatement(node); - case 224 /* ReturnStatement */: - return emitReturnStatement(node); - case 225 /* WithStatement */: - return emitWithStatement(node); - case 226 /* SwitchStatement */: - return emitSwitchStatement(node); - case 227 /* LabeledStatement */: - return emitLabeledStatement(node); - case 228 /* ThrowStatement */: - return emitThrowStatement(node); - case 229 /* TryStatement */: - return emitTryStatement(node); - case 230 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 231 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 232 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 233 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 234 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 235 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 236 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 237 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 238 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 239 /* ModuleBlock */: - return emitModuleBlock(node); - case 240 /* CaseBlock */: - return emitCaseBlock(node); - case 241 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 242 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 243 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 244 /* ImportClause */: - return emitImportClause(node); - case 245 /* NamespaceImport */: - return emitNamespaceImport(node); - case 246 /* NamedImports */: - return emitNamedImports(node); - case 247 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 248 /* ExportAssignment */: - return emitExportAssignment(node); - case 249 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 250 /* NamedExports */: - return emitNamedExports(node); - case 251 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 252 /* MissingDeclaration */: - return; - // Module references - case 253 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX (non-expression) - case 10 /* JsxText */: - return emitJsxText(node); - case 256 /* JsxOpeningElement */: - case 259 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 257 /* JsxClosingElement */: - case 260 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 261 /* JsxAttribute */: - return emitJsxAttribute(node); - case 262 /* JsxAttributes */: - return emitJsxAttributes(node); - case 263 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 264 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 265 /* CaseClause */: - return emitCaseClause(node); - case 266 /* DefaultClause */: - return emitDefaultClause(node); - case 267 /* HeritageClause */: - return emitHeritageClause(node); - case 268 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 269 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 270 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 271 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 272 /* EnumMember */: - return emitEnumMember(node); - // JSDoc nodes (ignored) - // Transformation nodes (ignored) - } - // If the node is an expression, try to emit it as an expression with - // substitution. - if (ts.isExpression(node)) { - return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); - } - if (ts.isToken(node)) { - writeTokenNode(node, writePunctuation); - return; - } - } - function pipelineEmitExpression(node) { - var kind = node.kind; - switch (kind) { - // Literals - case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; - // Expressions - case 182 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 183 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 184 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 185 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 186 /* CallExpression */: - return emitCallExpression(node); - case 187 /* NewExpression */: - return emitNewExpression(node); - case 188 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 189 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 190 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 191 /* FunctionExpression */: - return emitFunctionExpression(node); - case 192 /* ArrowFunction */: - return emitArrowFunction(node); - case 193 /* DeleteExpression */: - return emitDeleteExpression(node); - case 194 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 195 /* VoidExpression */: - return emitVoidExpression(node); - case 196 /* AwaitExpression */: - return emitAwaitExpression(node); - case 197 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 198 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 199 /* BinaryExpression */: - return emitBinaryExpression(node); - case 200 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 201 /* TemplateExpression */: - return emitTemplateExpression(node); - case 202 /* YieldExpression */: - return emitYieldExpression(node); - case 203 /* SpreadElement */: - return emitSpreadExpression(node); - case 204 /* ClassExpression */: - return emitClassExpression(node); - case 205 /* OmittedExpression */: - return; - case 207 /* AsExpression */: - return emitAsExpression(node); - case 208 /* NonNullExpression */: - return emitNonNullExpression(node); - case 209 /* MetaProperty */: - return emitMetaProperty(node); - // JSX - case 254 /* JsxElement */: - return emitJsxElement(node); - case 255 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 258 /* JsxFragment */: - return emitJsxFragment(node); - // Transformation nodes - case 296 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 297 /* CommaListExpression */: - return emitCommaList(node); - } + emit(node.constraint); } function trySubstituteNode(hint, node) { return node && substituteNode && substituteNode(hint, node) || node; @@ -74151,6 +75166,10 @@ var ts; writeStringLiteral(text); } } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + write(unparsed.text); + } // // Identifiers // @@ -74201,13 +75220,11 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.dotDotDotToken); - if (node.name) { - emitNodeWithWriter(node.name, writeParameter); - } - emitIfPresent(node.questionToken); - if (node.parent && node.parent.kind === 281 /* JSDocFunctionType */ && !node.name) { - emitIfPresent(node.type); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 283 /* JSDocFunctionType */ && !node.name) { + emit(node.type); } else { emitTypeAnnotation(node.type); @@ -74226,7 +75243,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeAnnotation(node.type); writeSemicolon(); } @@ -74234,28 +75251,30 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); - emitIfPresent(node.exclamationToken); + emit(node.questionToken); + emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -74272,14 +75291,17 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitCallSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitConstructSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("new"); @@ -74288,6 +75310,7 @@ var ts; emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); @@ -74314,18 +75337,20 @@ var ts; emitTypeArguments(node, node.typeArguments); } function emitFunctionType(node) { + pushNameGenerationScope(node); emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitJSDocFunctionType(node) { write("function"); emitParameters(node, node.parameters); write(":"); - emitIfPresent(node.type); + emit(node.type); } function emitJSDocNullableType(node) { write("?"); @@ -74340,6 +75365,7 @@ var ts; write("="); } function emitConstructorType(node) { + pushNameGenerationScope(node); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -74347,7 +75373,8 @@ var ts; writeSpace(); writePunctuation("=>"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); + popNameGenerationScope(node); } function emitTypeQuery(node) { writeKeyword("typeof"); @@ -74437,7 +75464,8 @@ var ts; writeSpace(); } writePunctuation("["); - pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); @@ -74447,7 +75475,7 @@ var ts; } writePunctuation(":"); writeSpace(); - emitIfPresent(node.type); + emit(node.type); writeSemicolon(); if (emitFlags & 1 /* SingleLine */) { writeSpace(); @@ -74490,7 +75518,7 @@ var ts; writePunctuation("]"); } function emitBindingElement(node) { - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); if (node.propertyName) { emit(node.propertyName); writePunctuation(":"); @@ -74508,6 +75536,7 @@ var ts; emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); @@ -74597,6 +75626,7 @@ var ts; emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { @@ -74696,7 +75726,7 @@ var ts; } function emitYieldExpression(node) { emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { @@ -74704,6 +75734,7 @@ var ts; emitExpression(node.expression); } function emitClassExpression(node) { + generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { @@ -74757,7 +75788,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - writeSemicolon(); + if (!ts.isJsonSourceFile(currentSourceFile)) { + writeSemicolon(); + } } function emitIfStatement(node) { var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); @@ -74953,7 +75986,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -74970,6 +76003,8 @@ var ts; increaseIndent(); } pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); emitSignatureHead(node); if (onEmitNode) { onEmitNode(4 /* Unspecified */, body, emitBlockCallback); @@ -75065,6 +76100,7 @@ var ts; emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("class"); @@ -75142,6 +76178,7 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); popNameGenerationScope(node); } @@ -75183,12 +76220,12 @@ var ts; writeSemicolon(); } function emitImportClause(node) { - emitIfPresent(node.name); + emit(node.name); if (node.name && node.namedBindings) { emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node); writeSpace(); } - emitIfPresent(node.namedBindings); + emit(node.namedBindings); } function emitNamespaceImport(node) { var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node); @@ -75330,7 +76367,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { writePunctuation("{"); - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); emitExpression(node.expression); writePunctuation("}"); } @@ -75486,8 +76523,8 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { - var directive = types_18[_d]; + for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { + var directive = types_17[_d]; write("/// "); writeLine(); } @@ -75495,6 +76532,7 @@ var ts; function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); @@ -75571,6 +76609,8 @@ var ts; // Helpers // function emitNodeWithWriter(node, writer) { + if (!node) + return; var savedWrite = write; write = writer; emit(node); @@ -76060,7 +77100,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return generateName(node); } - else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { @@ -76112,6 +77152,113 @@ var ts; } reservedNames.set(name, true); } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 212 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 227 /* LabeledStatement */: + case 225 /* WithStatement */: + case 217 /* DoStatement */: + case 218 /* WhileStatement */: + generateNames(node.statement); + break; + case 216 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 219 /* ForStatement */: + case 221 /* ForOfStatement */: + case 220 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 226 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 240 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 265 /* CaseClause */: + case 266 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 229 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 268 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 213 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 232 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 231 /* VariableDeclaration */: + case 148 /* Parameter */: + case 181 /* BindingElement */: + case 234 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 233 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 179 /* ObjectBindingPattern */: + case 180 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 243 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 244 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 245 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 246 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 247 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 269 /* PropertyAssignment */: + case 270 /* ShorthandPropertyAssignment */: + case 151 /* PropertyDeclaration */: + case 153 /* MethodDeclaration */: + case 155 /* GetAccessor */: + case 156 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } /** * Generate the text for a generated identifier. */ @@ -76119,17 +77266,7 @@ var ts; if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { - var savedTempFlags = tempFlags; - popNameGenerationScope(/*node*/ undefined); - var result = generateNameCached(getNodeForGeneratedName(name)); - pushNameGenerationScope(/*node*/ undefined); - tempFlags = savedTempFlags; - return result; - } - else { - return generateNameCached(getNodeForGeneratedName(name)); - } + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); } else { // Auto, Loop, and Unique names are cached based on their unique @@ -76138,9 +77275,9 @@ var ts; return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } - function generateNameCached(node) { + function generateNameCached(node, flags) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); } /** * Returns a value indicating whether a name is unique globally, within the current file, @@ -76155,7 +77292,7 @@ var ts; * Returns a value indicating whether a name is unique globally or within the current file. */ function isFileLevelUniqueName(name) { - return ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName); + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; } /** * Returns a value indicating whether a name is unique within a container. @@ -76212,11 +77349,16 @@ var ts; * makeUniqueName are guaranteed to never conflict. * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName, checkFn, optimistic) { + function makeUniqueName(baseName, checkFn, optimistic, scoped) { if (checkFn === void 0) { checkFn = isUniqueName; } if (optimistic) { if (checkFn(baseName)) { - generatedNames.set(baseName, true); + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } return baseName; } } @@ -76228,7 +77370,12 @@ var ts; while (true) { var generatedName = baseName + i; if (checkFn(generatedName)) { - generatedNames.set(generatedName, true); + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } return generatedName; } i++; @@ -76275,10 +77422,10 @@ var ts; /** * Generates a unique name from a node. */ - function generateNameForNode(node) { + function generateNameForNode(node, flags) { switch (node.kind) { case 71 /* Identifier */: - return makeUniqueName(getTextOfNode(node)); + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); case 238 /* ModuleDeclaration */: case 237 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); @@ -76305,11 +77452,11 @@ var ts; function makeName(name) { switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 3 /* Unique */: - return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 64 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 32 /* Optimistic */)); + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -76325,7 +77472,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateFlags === 4 /* Node */ + && !!(node.autoGenerateFlags & 4 /* Node */) && node.autoGenerateId !== autoGenerateId) { break; } @@ -76384,7 +77531,7 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); } function getCachedFileSystemEntriesForBaseDir(path) { return getCachedFileSystemEntries(ts.getDirectoryPath(path)); @@ -76397,7 +77544,7 @@ var ts; files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], directories: host.getDirectories(rootDir) || [] }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); return resultFromHost; } /** @@ -76406,6 +77553,7 @@ var ts; * The host request is done under try catch block to avoid caching incorrect result */ function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); var cachedResult = getCachedFileSystemEntries(rootDirPath); if (cachedResult) { return cachedResult; @@ -76415,7 +77563,7 @@ var ts; } catch (_e) { // If there is exception to read directories, dont cache the result and direct the calls to host - ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); return undefined; } } @@ -76451,7 +77599,7 @@ var ts; } function directoryExists(dirPath) { var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); } function createDirectory(dirPath) { var path = toPath(dirPath); @@ -76725,7 +77873,7 @@ var ts; if (!commonPathComponents) { // Can happen when all input files are .d.ts files return currentDirectory; } - return ts.getNormalizedPathFromPathComponents(commonPathComponents); + return ts.getPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { @@ -76832,7 +77980,8 @@ var ts; directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, - realpath: realpath + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); } }; } ts.createCompilerHost = createCompilerHost; @@ -76900,52 +78049,52 @@ var ts; var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; - var context = ""; + var context_2 = ""; if (diagnostic.file) { - var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; - var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var start = diagnostic.start, length_4 = diagnostic.length, file_9 = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file_9, start + length_4), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file_9, file_9.text.length).line; + var relativeFileName = host ? ts.convertToRelativePath(file_9.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_9.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; var gutterWidth = (lastLine + 1 + "").length; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } for (var i = firstLine; i <= lastLine; i++) { - context += host.getNewLine(); + context_2 += host.getNewLine(); // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context_2 += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); + var lineStart = ts.getPositionOfLineAndCharacter(file_9, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file_9, i + 1, 0) : file_9.text.length; + var lineContent = file_9.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += lineContent + host.getNewLine(); + context_2 += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context_2 += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += ForegroundColorEscapeSequences.Red; + context_2 += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context_2 += ForegroundColorEscapeSequences.Red; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. var lastCharForLine = i === lastLine ? lastLineChar : undefined; - context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + context_2 += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context_2 += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); } else if (i === lastLine) { - context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + context_2 += lineContent.slice(0, lastLineChar).replace(/./g, "~"); } else { // Squiggle the entire line. - context += lineContent.replace(/./g, "~"); + context_2 += lineContent.replace(/./g, "~"); } - context += resetEscapeSequence; + context_2 += resetEscapeSequence; } output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); output += ":"; @@ -76959,7 +78108,7 @@ var ts; output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); - output += context; + output += context_2; } output += host.getNewLine(); } @@ -77069,21 +78218,19 @@ var ts; oldOptions.baseUrl !== newOptions.baseUrl || !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); } - /** - * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' - * that represent a compilation unit. - * - * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and - * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. - * - * @param rootNames - A set of root files. - * @param options - The compiler options which should be used. - * @param host - The host interacts with the underlying file system. - * @param oldProgram - Reuses an old program structure. - * @param configFileParsingDiagnostics - error during config file parsing - * @returns A 'Program' object. - */ - function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -77111,6 +78258,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -77120,6 +78268,7 @@ var ts; // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; + var _referencesArrayLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; @@ -77159,6 +78308,23 @@ var ts; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences = projectReferences ? [] : undefined; + var projectReferenceRedirects = ts.createMap(); + if (projectReferences) { + for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { + var ref = projectReferences_1[_i]; + var parsedRef = parseProjectReferenceConfigFile(ref); + resolvedProjectReferences.push(parsedRef); + if (parsedRef) { + if (parsedRef.commandLine.options.outFile) { + var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*packageId*/ undefined); + } + addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + } + } + } var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -77198,8 +78364,8 @@ var ts; // not part of the new program. if (oldProgram && host.onReleaseOldSourceFile) { var oldSourceFiles = oldProgram.getSourceFiles(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); } @@ -77240,6 +78406,7 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -77255,9 +78422,14 @@ var ts; if (commonSourceDirectory === undefined) { var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { - // If a rootDir is specified and is valid use it as the commonSourceDirectory + // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } + else if (options.composite) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } else { commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } @@ -77295,16 +78467,16 @@ var ts; // We only set `file.resolvedModules` via work from the current function, // so it is defined iff we already called the current function on `file`. // That call happened no later than the creation of the `file` object, - // which per above occured during the current program creation. + // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -77435,6 +78607,34 @@ var ts; if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { return oldProgram.structureIsReused = 0 /* Not */; } + // Check if any referenced project tsconfig files are different + var oldRefs = oldProgram.getProjectReferences(); + if (projectReferences) { + if (!oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + for (var i = 0; i < projectReferences.length; i++) { + var oldRef = oldRefs[i]; + if (oldRef) { + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); + if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { + // Resolved project reference has gone missing or changed + return oldProgram.structureIsReused = 0 /* Not */; + } + } + else { + // A previously-unresolved reference may be resolved now + if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } + } + } + else { + if (oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; @@ -77602,6 +78802,7 @@ var ts; } function getEmitHost(writeFileCallback) { return { + getPrependNodes: getPrependNodes, getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, @@ -77615,6 +78816,32 @@ var ts; isEmitBlocked: isEmitBlocked, }; } + function getProjectReferences() { + if (!resolvedProjectReferences) + return; + return resolvedProjectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!resolvedRefOpts.options.outFile) + continue; + var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); + var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var node = ts.createInputFiles(js, dts); + nodes.push(node); + } + } + return nodes; + } function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } @@ -77685,7 +78912,7 @@ var ts; var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -77769,9 +78996,9 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); - // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || - sourceFile.scriptKind === 5 /* External */ || isCheckJs; + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -78147,7 +79374,13 @@ var ts; var sourceFile = getSourceFile(fileName); if (fail) { if (!sourceFile) { - fail(ts.Diagnostics.File_0_not_found, fileName); + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); @@ -78208,31 +79441,45 @@ var ts; // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { - var file_1 = filesByName.get(path); + var file_10 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + if (file_10 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_10.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(fileName, file_10.fileName, refFile, refPos, refEnd); } // If the file was previously found via a node_modules search, but is now being processed as a root file, // then everything it sucks in may also be marked incorrectly, and needs to be checked again. - if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { - sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (file_10 && sourceFilesFoundSearchingNodeModules.get(file_10.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_10.path, false); if (!options.noResolve) { - processReferencedFiles(file_1, isDefaultLib); - processTypeReferenceDirectives(file_1); + processReferencedFiles(file_10, isDefaultLib); + processTypeReferenceDirectives(file_10); } - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); + modulesWithElidedImports.set(file_10.path, false); + processImportedModules(file_10); } // See if we need to reprocess the imports due to prior skipped imports - else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + else if (file_10 && modulesWithElidedImports.get(file_10.path)) { if (currentNodeModulesDepth < maxNodeModuleJsDepth) { - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); + modulesWithElidedImports.set(file_10.path, false); + processImportedModules(file_10); } } - return file_1; + return file_10; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } } // We haven't looked for this file, do so now and cache result var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { @@ -78263,6 +79510,9 @@ var ts; } } filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; @@ -78293,6 +79543,22 @@ var ts; } return file; } + function getProjectReferenceRedirect(fileName) { + var path = toPath(fileName); + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var normalized = ts.getNormalizedAbsolutePath(fileName, path); + var result; + projectReferenceRedirects.forEach(function (v, k) { + if (result !== undefined) { + return undefined; + } + if (normalized.indexOf(k) === 0) { + result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); + } + }); + return result; + } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); @@ -78302,6 +79568,9 @@ var ts; function processTypeReferenceDirectives(file) { // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; @@ -78381,7 +79650,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -78423,9 +79692,9 @@ var ts; function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); + var file_11 = sourceFiles_2[_i]; + if (!file_11.isDeclarationFile) { + fileNames.push(file_11.fileName); } } return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); @@ -78447,6 +79716,27 @@ var ts; } return allFilesBelongToPath; } + function parseProjectReferenceConfigFile(ref) { + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(host, ref); + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + if (sourceFile === undefined) { + return undefined; + } + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + return { commandLine: commandLine, sourceFile: sourceFile }; + } + function addProjectReferenceRedirects(referencedProject, target) { + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); + target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); + } + function getDeclarationOutputDirectory(proj) { + return proj.options.declarationDir || + proj.options.outDir || + ts.getDirectoryPath(proj.options.configFilePath); + } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !options.strictNullChecks) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); @@ -78476,6 +79766,48 @@ var ts; if (options.paths && options.baseUrl === undefined) { createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + if (projectReferences) { + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; + if (resolvedRefOpts === undefined) { + createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); + continue; + } + if (!resolvedRefOpts.composite) { + createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + if (ref.prepend) { + if (resolvedRefOpts.outFile) { + if (!host.fileExists(resolvedRefOpts.outFile)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + } + } + else { + createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + } + } + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite && rootNames.length < files.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); + var _loop_10 = function (file_12) { + if (normalizedRootNames.every(function (r) { return r !== file_12; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file_12)); + } + }; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var file_12 = sourceFiles_4[_i]; + _loop_10(file_12); + } + } if (options.paths) { for (var key in options.paths) { if (!ts.hasProperty(options.paths, key)) { @@ -78567,6 +79899,11 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified @@ -78679,12 +80016,15 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); } } - function getOptionPathsSyntax() { + function getOptionsSyntaxByName(name) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); if (compilerOptionsObjectLiteralSyntax) { - return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); } - return ts.emptyArray; + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; } function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); @@ -78692,6 +80032,15 @@ var ts; function createOptionValueDiagnostic(option1, message, arg0) { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } + function createDiagnosticForReference(index, message, arg0, arg1) { + var referencesSyntax = getProjectReferencesSyntax(); + if (referencesSyntax) { + if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { + return; + } + } + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || @@ -78700,11 +80049,28 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); } } + function getProjectReferencesSyntax() { + if (_referencesArrayLiteralSyntax === undefined) { + _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword + if (options.configFile) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isArrayLiteralExpression(prop.initializer)) { + _referencesArrayLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _referencesArrayLiteralSyntax; + } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile && options.configFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { var prop = _a[_i]; if (ts.isObjectLiteralExpression(prop.initializer)) { _compilerOptionsObjectLiteralSyntax = prop.initializer; @@ -78723,6 +80089,13 @@ var ts; } return !!props.length; } + function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { + if (arrayLiteral.elements.length <= index) { + // Out-of-bounds + return false; + } + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -78759,6 +80132,27 @@ var ts; } ts.createProgram = createProgram; /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + /** + * Returns the target config filename of a project reference + */ + function resolveProjectReferencePath(host, ref) { + if (!host.fileExists(ref.path)) { + return ts.combinePaths(ref.path, "tsconfig.json"); + } + return ref.path; + } + /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. @@ -78769,6 +80163,7 @@ var ts; switch (extension) { case ".ts" /* Ts */: case ".d.ts" /* Dts */: + case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check // These are always allowed. return undefined; case ".tsx" /* Tsx */: @@ -78969,6 +80364,7 @@ var ts; * Get all the dependencies of the sourceFile */ function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; var compilerOptions = programOfThisState.getCompilerOptions(); // With --out or --outFile all outputs go into single file, all files depend on each other if (compilerOptions.outFile || compilerOptions.out) { @@ -78988,7 +80384,7 @@ var ts; var references = state.referencedMap.get(path); if (references) { var iterator = references.keys(); - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { queue.push(value); } } @@ -78998,7 +80394,6 @@ var ts; var file = programOfThisState.getSourceFileByPath(path); return file ? file.fileName : path; })); - var _b; } BuilderState.getAllDependencies = getAllDependencies; /** @@ -79443,8 +80838,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_1 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -79522,6 +80917,7 @@ var ts; startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, @@ -79694,6 +81090,10 @@ var ts; function resolveModuleNames(moduleNames, containingFile, reusedNames) { return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } @@ -79741,17 +81141,19 @@ var ts; return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } // Use some ancestor of the root directory + var subDirectory; if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { var parentPath = ts.getDirectoryPath(dirPath); if (parentPath === dirPath) { break; } + subDirectory = dirPath.slice(parentPath.length + ts.directorySeparator.length); dirPath = parentPath; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath, subDirectory: subDirectory }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -79771,7 +81173,7 @@ var ts; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { // If the failed lookup location path is not one of the supported extensions, // store it in the custom path @@ -79783,7 +81185,7 @@ var ts; setAtRoot = true; } else { - setDirectoryWatcher(dir, dirPath); + setDirectoryWatcher(dir, dirPath, subDirectory); } } } @@ -79791,13 +81193,19 @@ var ts; setDirectoryWatcher(rootDir, rootPath); } } - function setDirectoryWatcher(dir, dirPath) { + function setDirectoryWatcher(dir, dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { dirWatcher.refCount++; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }; + directoryWatchesOfFailedLookups.set(dirPath, dirWatcher); + } + if (subDirectory) { + var subDirectoryMap = dirWatcher.subDirectoryMap || (dirWatcher.subDirectoryMap = ts.createMap()); + var existing = subDirectoryMap.get(subDirectory) || 0; + subDirectoryMap.set(subDirectory, existing + 1); } } function stopWatchFailedLookupLocationOfResolution(resolution) { @@ -79813,7 +81221,7 @@ var ts; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { var failedLookupLocation = failedLookupLocations_2[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory; if (!ignore) { var refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { @@ -79829,7 +81237,7 @@ var ts; removeAtRoot = true; } else { - removeDirectoryWatcher(dirPath); + removeDirectoryWatcher(dirPath, subDirectory); } } } @@ -79837,22 +81245,40 @@ var ts; removeDirectoryWatcher(rootPath); } } - function removeDirectoryWatcher(dirPath) { + function removeDirectoryWatcher(dirPath, subDirectory) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (subDirectory) { + var existing = dirWatcher.subDirectoryMap.get(subDirectory); + if (existing === 1) { + dirWatcher.subDirectoryMap.delete(subDirectory); + } + else { + dirWatcher.subDirectoryMap.set(subDirectory, existing - 1); + } + } // Do not close the watcher yet since it might be needed by other failed lookup locations. dirWatcher.refCount--; } + function inWatchedSubdirectory(dirPath, fileOrDirectoryPath) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (!dirWatcher || !dirWatcher.subDirectoryMap) + return false; + return ts.forEachKey(dirWatcher.subDirectoryMap, function (subDirectory) { + var fullSubDirectory = dirPath + "/" + subDirectory; + return fullSubDirectory === fileOrDirectoryPath || isInDirectoryPath(fullSubDirectory, fileOrDirectoryPath); + }); + } function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // If the files are added to project root or node_modules directory, always run through the invalidation process // Otherwise run through invalidation only if adding to the immediate directory if (!allFilesHaveInvalidatedResolution && - dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + (dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath || inWatchedSubdirectory(dirPath, fileOrDirectoryPath))) { if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { resolutionHost.onInvalidatedResolution(); } @@ -79976,7 +81402,7 @@ var ts; return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // For now just recompile @@ -80112,34 +81538,11 @@ var ts; function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; - var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - /** - * Reads the config file, reports errors if any and exits if the config file cannot be found - */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - var result = ts.parseJsonText(configFileName, configFileText); - var cwd = host.getCurrentDirectory(); - return ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); - } - ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ @@ -80221,12 +81624,12 @@ var ts; watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, setTimeout: system.setTimeout ? (function (callback, ms) { + var _a; var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - var _a; }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, trace: function (s) { return system.write(s); }, @@ -80986,6 +82389,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, { name: "removeComments", type: "boolean", @@ -81246,6 +82656,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, { name: "listFiles", type: "boolean", @@ -81539,11 +82955,13 @@ var ts; function parseCommandLine(commandLine, readFile) { var options = {}; var fileNames = []; + var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, + projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -81656,6 +83074,29 @@ var ts; } return optionNameMap.get(optionName); } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -81703,55 +83144,67 @@ var ts; var _tsconfigRootOptions; function getTsconfigRootOptionsMap() { if (_tsconfigRootOptions === undefined) { - _tsconfigRootOptions = commandLineOptionsToMap([ - { - name: "compilerOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 - }, - { - name: "typingOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "typeAcquisition", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "extends", - type: "string" - }, - { - name: "files", - type: "list", - element: { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { name: "files", - type: "string" - } - }, - { - name: "include", - type: "list", - element: { + type: "list", + element: { + name: "files", + type: "string" + } + }, + { name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { + type: "list", + element: { + name: "include", + type: "string" + } + }, + { name: "exclude", - type: "string" - } - }, - ts.compileOnSaveCommandLineOption - ]); + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; } return _tsconfigRootOptions; } @@ -81759,20 +83212,25 @@ var ts; * Convert the json syntax tree into the json value */ function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } ts.convertToObject = convertToObject; /** - * Convert the json syntax tree into the json value + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined */ - function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.jsonObject) { - return {}; + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, - /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined); function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { - var result = {}; + var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; if (element.kind !== 269 /* PropertyAssignment */) { @@ -81792,11 +83250,13 @@ var ts; } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { - result[keyText] = value; + if (returnValue) { + result[keyText] = value; + } // Notify key value set, if user asked for it if (jsonConversionNotifier && // Current callbacks are only on known parent option or if we are setting values in the root - (parentOption || knownOptions === knownRootOptions)) { + (parentOption || isRootOptionMap(knownOptions))) { var isValidOptionValue = isCompilerOptionsValue(option, value); if (parentOption) { if (isValidOptionValue) { @@ -81804,7 +83264,7 @@ var ts; jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); } } - else if (knownOptions === knownRootOptions) { + else if (isRootOptionMap(knownOptions)) { if (isValidOptionValue) { // Notify about the valid root key value being set jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); @@ -81820,7 +83280,7 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -81895,6 +83355,7 @@ var ts; return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } + ts.convertToObjectWorker = convertToObjectWorker; function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : @@ -81944,7 +83405,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_9 = function (name) { + var _loop_11 = function (name) { if (ts.hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean @@ -81973,7 +83434,7 @@ var ts; } }; for (var name in options) { - _loop_9(name); + _loop_11(name); } return result; } @@ -82123,12 +83584,13 @@ var ts; var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); - options.configFilePath = configFileName; + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; return { options: options, fileNames: fileNames, + projectReferences: projectReferences, typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), raw: raw, errors: errors, @@ -82167,19 +83629,43 @@ var ts; createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } - else { - var outDir = raw.compilerOptions && raw.compilerOptions.outDir; - if (outDir) { - excludeSpecs = [outDir]; + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); } } if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + var references = []; + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + references.push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + result.projectReferences = references; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } return result; } function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { @@ -82297,7 +83783,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -82332,6 +83818,7 @@ var ts; return extendedConfigPath; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -82360,7 +83847,6 @@ var ts; mapPropertiesInRawIfNotUndefined("files"); } return extendedConfig; - var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { @@ -82385,7 +83871,7 @@ var ts; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function getDefaultCompilerOptions(configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {}; return options; @@ -82393,10 +83879,13 @@ var ts; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -82557,7 +84046,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -82591,37 +84080,41 @@ var ts; if (filesSpecs) { for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { var fileName = filesSpecs_1[_i]; - var file = ts.getNormalizedAbsolutePath(fileName, basePath); - literalFileMap.set(keyMapper(file), file); + var file_13 = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file_13), file_13); } } if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var file_14 = _b[_a]; // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // // This handles cases where we may encounter both .ts and // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. - if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + if (hasFileWithHigherPriorityExtension(file_14, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the // "include" array. If there is a lower priority extension in the // same directory, we should remove it. - removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); - var key = keyMapper(file); + removeWildcardFilesWithLowerPriorityExtension(file_14, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file_14); if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { - wildcardFileMap.set(key, file); + wildcardFileMap.set(key, file_14); } } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { + return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); + }); return { fileNames: literalFiles.concat(wildcardFiles), + projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -82636,20 +84129,10 @@ var ts; return diag === undefined; }); function createDiagnostic(message, spec) { - if (jsonSourceFile && jsonSourceFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { - var property = _a[_i]; - if (ts.isArrayLiteralExpression(property.initializer)) { - for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (ts.isStringLiteral(element) && element.text === spec) { - return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); - } - } - } - } - } - return ts.createCompilerDiagnostic(message, spec); + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); } } function specToDiagnostic(spec, allowTrailingRecursion) { @@ -82682,8 +84165,8 @@ var ts; if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { - var file = include_1[_i]; - var spec = ts.normalizePath(ts.combinePaths(path, file)); + var file_15 = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file_15)); if (excludeRegex && excludeRegex.test(spec)) { continue; } @@ -82877,6 +84360,17 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + /** Single or multi-line comments */ + OutliningSpanKind["Comment"] = "comment"; + /** Sections marked by '// #region' and '// #endregion' comments */ + OutliningSpanKind["Region"] = "region"; + /** Declarations and expressions */ + OutliningSpanKind["Code"] = "code"; + /** Contiguous blocks of import declarations */ + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); var OutputFileType; (function (OutputFileType) { OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; @@ -82972,6 +84466,8 @@ var ts; * */ ScriptElementKind["jsxAttribute"] = "JSX attribute"; + /** String literal */ + ScriptElementKind["string"] = "string"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -83077,7 +84573,7 @@ var ts; case 236 /* TypeAliasDeclaration */: case 165 /* TypeLiteral */: return 2 /* Type */; - case 292 /* JSDocTypedefTag */: + case 296 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; case 272 /* EnumMember */: @@ -83131,6 +84627,10 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName return 2 /* Type */; } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } else { return 1 /* Value */; } @@ -83193,6 +84693,8 @@ var ts; switch (node.parent.kind) { case 161 /* TypeReference */: return true; + case 178 /* ImportType */: + return !node.parent.isTypeOf; case 206 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } @@ -83280,7 +84782,7 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 292 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(node)) { // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. // Then we get parent again in the loop. @@ -83318,7 +84820,10 @@ var ts; case 204 /* ClassExpression */: return "class" /* classElement */; case 235 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 236 /* TypeAliasDeclaration */: return "type" /* typeElement */; + case 236 /* TypeAliasDeclaration */: + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + return "type" /* typeElement */; case 237 /* EnumDeclaration */: return "enum" /* enumElement */; case 231 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); @@ -83349,8 +84854,6 @@ var ts; case 251 /* ExportSpecifier */: case 245 /* NamespaceImport */: return "alias" /* alias */; - case 292 /* JSDocTypedefTag */: - return "type" /* typeElement */; case 199 /* BinaryExpression */: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; @@ -83412,6 +84915,10 @@ var ts; return startEndContainsRange(r1.pos, r1.end, r2); } ts.rangeContainsRange = rangeContainsRange; + function rangeContainsPosition(r, pos) { + return r.pos <= pos && pos <= r.end; + } + ts.rangeContainsPosition = rangeContainsPosition; function startEndContainsRange(start, end, range) { return start <= range.pos && end >= range.end; } @@ -83678,7 +85185,7 @@ var ts; return findPrecedingToken(position, file); } ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { + function findNextToken(previousToken, parent, sourceFile) { return find(parent); function find(n) { if (ts.isToken(n) && n.pos === previousToken.end) { @@ -83693,7 +85200,7 @@ var ts; (child.pos <= previousToken.pos && child.end > previousToken.end) || // previous token ends exactly at the beginning of child (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { + if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) { return find(child); } } @@ -83724,11 +85231,11 @@ var ts; if (position < child.end) { var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || // cursor in the leading trivia - !nodeHasTokens(child) || + !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } else { @@ -83743,7 +85250,7 @@ var ts; // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } } @@ -83757,19 +85264,19 @@ var ts; return n; } var children = n.getChildren(sourceFile); - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } /** * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. */ - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { var child = children[i]; if (isWhiteSpaceOnlyJsxText(child)) { ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); } - else if (nodeHasTokens(children[i])) { + else if (nodeHasTokens(children[i], sourceFile)) { return children[i]; } } @@ -83881,22 +85388,22 @@ var ts; remainingLessThanTokens++; break; case 18 /* CloseBraceToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); if (!token) return false; break; case 20 /* CloseParenToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); if (!token) return false; break; case 22 /* CloseBracketToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); if (!token) return false; @@ -83950,10 +85457,10 @@ var ts; } } ts.hasDocComment = hasDocComment; - function nodeHasTokens(n) { + function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth() !== 0; + return n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.getCombinedModifierFlags(node); @@ -84050,11 +85557,6 @@ var ts; return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); @@ -84077,6 +85579,10 @@ var ts; return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createTextRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { return createTextChange(ts.createTextSpan(start, length), newText); } @@ -84109,7 +85615,6 @@ var ts; return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; - /** Returns `true` the first time it encounters a node and `false` afterwards. */ function nodeSeenTracker() { var seen = []; return function (node) { @@ -84157,6 +85662,63 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + } + ts.makeImport = makeImport; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default" /* Default */) { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { + // See GH#16922 + ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); + return propSymbol.target; + } + return propSymbol; + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -84489,20 +86051,20 @@ var ts; * user was before extracting it. */ /* @internal */ - function getRenameLocation(edits, renameFilename, name, isDeclaredBeforeUse) { + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { var delta = 0; var lastPos = -1; for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; ts.Debug.assert(fileName === renameFilename); - for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { - var change = textChanges_2[_b]; + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; var span = change.span, newText = change.newText; var index = newText.indexOf(name); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. - if (!isDeclaredBeforeUse) { + if (!preferLastLocation) { return lastPos; } } @@ -84510,7 +86072,7 @@ var ts; } } // If the declaration comes first, return the position of the last occurrence. - ts.Debug.assert(isDeclaredBeforeUse); + ts.Debug.assert(preferLastLocation); ts.Debug.assert(lastPos >= 0); return lastPos; } @@ -85158,20 +86720,22 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 288 /* JSDocParameterTag */: + case 292 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); + pos = tag.end; break; - case 290 /* JSDocTypeTag */: + case 294 /* JSDocTypeTag */: processElement(tag.typeExpression); + pos = tag.end; break; - case 289 /* JSDocReturnTag */: + case 293 /* JSDocReturnTag */: processElement(tag.typeExpression); + pos = tag.end; break; } - pos = tag.end; } } if (pos !== docComment.end) { @@ -85413,7 +86977,7 @@ var ts; var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = ts.getSupportedExtensions(compilerOptions); + var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); } @@ -85426,6 +86990,12 @@ var ts; return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json" /* Json */) : + extensions; + } /** * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option @@ -85464,13 +87034,16 @@ var ts; * Remove the basename from the path. Note that we don't use the basename to filter completions; * the client is responsible for refining completions. */ - fragment = ts.getDirectoryPath(fragment); + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } if (fragment === "") { fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); - var baseDirectory = ts.getDirectoryPath(absolutePath); + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (tryDirectoryExists(host, baseDirectory)) { // Enumerate the available files if possible @@ -85489,7 +87062,7 @@ var ts; if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; } - var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } @@ -85502,8 +87075,8 @@ var ts; var directories = tryGetDirectories(host, baseDirectory); if (directories) { for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var directory = directories_1[_a]; - var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); + var directory_2 = directories_1[_a]; + var directoryName = ts.getBaseFileName(ts.normalizePath(directory_2)); if (directoryName !== "@types") { result.push(nameAndKind(directoryName, "directory" /* directory */)); } @@ -85522,7 +87095,7 @@ var ts; function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); @@ -85530,7 +87103,7 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_10 = function (name, kind) { + var _loop_12 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind)); @@ -85538,12 +87111,12 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_10(name, kind); + _loop_12(name, kind); } } } } - var fragmentDirectory = containsSlash(fragment) ? ts.getDirectoryPath(fragment) : undefined; + var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { var ambientName = _d[_c]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); @@ -85554,7 +87127,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_11 = function (moduleName) { + var _loop_13 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); @@ -85562,7 +87135,7 @@ var ts; }; for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { var moduleName = _f[_e]; - _loop_11(moduleName); + _loop_13(moduleName); } } if (!foundGlobal) { @@ -85598,12 +87171,13 @@ var ts; } // The prefix has two effective parts: the directory path and the base component after the filepath that is not a // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); var fragmentHasPath = containsSlash(fragment); + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); @@ -85764,15 +87338,6 @@ var ts; } return false; } - function normalizeAndPreserveTrailingSlash(path) { - if (ts.normalizeSlashes(path) === "./") { - // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case. - // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning. - return ""; - } - var norm = ts.normalizePath(path); - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; - } /** * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment @@ -85892,7 +87457,7 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); }); + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: @@ -86459,11 +88024,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 275 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 277 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 293 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 297 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -86599,12 +88164,8 @@ var ts; } else if (isRightOfOpenTag) { var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); - if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 /* Value */ | 2097152 /* Alias */)); })); - } - else { - symbols = tagSymbols; - } + tryGetGlobalSymbols(); + symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; } else if (isStartingCloseTag) { @@ -86628,11 +88189,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 288 /* JSDocParameterTag */: - case 293 /* JSDocPropertyTag */: - case 289 /* JSDocReturnTag */: - case 290 /* JSDocTypeTag */: - case 292 /* JSDocTypedefTag */: + case 292 /* JSDocParameterTag */: + case 297 /* JSDocPropertyTag */: + case 293 /* JSDocReturnTag */: + case 294 /* JSDocTypeTag */: + case 296 /* JSDocTypedefTag */: return true; } } @@ -86894,7 +88455,7 @@ var ts; var exportedSymbols = typeChecker.getExportsOfModule(symbol); // If the exported symbols contains type, // symbol can be referenced at locations where type is allowed - return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); + return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); } } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { @@ -87670,7 +89231,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 294 /* SyntaxList */: + case 298 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -87707,6 +89268,9 @@ var ts; } function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { switch (triggerCharacter) { + case ".": + case "@": + return true; case '"': case "'": case "`": @@ -87715,8 +89279,12 @@ var ts; case "<": // Opening JSX tag return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */; + case "/": + return ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); default: - return ts.Debug.fail(triggerCharacter); + return ts.Debug.assertNever(triggerCharacter); } } function isStringLiteralOrTemplate(node) { @@ -87811,6 +89379,10 @@ var ts; case 125 /* GetKeyword */: case 136 /* SetKeyword */: return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]); + case 121 /* AwaitKeyword */: + return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); + case 120 /* AsyncKeyword */: + return highlightSpans(getAsyncAndAwaitOccurrences(node)); default: return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) @@ -88058,6 +89630,29 @@ var ts; }); return keywords; } + function getAsyncAndAwaitOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + if (func.modifiers) { + func.modifiers.forEach(function (modifier) { + pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */); + }); + } + ts.forEachChild(func, aggregate); + return keywords; + function aggregate(node) { + if (ts.isAwaitExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */); + } + // Do not cross function boundaries. + if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) { + ts.forEachChild(node, aggregate); + } + } + } function getIfElseOccurrences(ifStatement, sourceFile) { var keywords = getIfElseKeywords(ifStatement, sourceFile); var result = []; @@ -88178,9 +89773,10 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); entry = { sourceFile: sourceFile, languageServiceRefCount: 1, @@ -88309,6 +89905,8 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; + case 71 /* Identifier */: // for 'const x = require("y"); + break; // TODO: GH#23879 case 242 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */)); break; @@ -88338,6 +89936,11 @@ var ts; directImports.push(direct); } break; + case 178 /* ImportType */: + directImports.push(direct); + break; + default: + ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); } } } @@ -88415,6 +90018,14 @@ var ts; return; } if (decl.kind === 178 /* ImportType */) { + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); + } return; } // Ignore if there's a grammar error @@ -88442,7 +90053,7 @@ var ts; var name = importClause.name; // If a default import has the same name as the default export, allow to rename it. // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. - if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { + if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { var defaultImportAlias = checker.getSymbolAtLocation(name); addSearch(name, defaultImportAlias); } @@ -88500,24 +90111,18 @@ var ts; function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { - if (statement.kind !== 249 /* ExportDeclaration */) + if (!ts.isExportDeclaration(statement)) return; - var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier; - if (moduleSpecifier || !exportClause) - return; - for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) { - var element = _b[_i]; - if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) { - return true; - } - } + var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; + return !moduleSpecifier && exportClause && + exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; }); }); } function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var referencingFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var referencingFile = sourceFiles_5[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 273 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -88547,8 +90152,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -88653,6 +90258,9 @@ var ts; else if (ts.isBinaryExpression(parent.parent)) { return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); } + else if (ts.isJSDocTypedefTag(parent)) { + return exportInfo(symbol, 0 /* Named */); + } } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. @@ -88697,7 +90305,7 @@ var ts; // If the import has a different name than the export, do not continue searching. // If `importedName` is undefined, do continue searching as the export is anonymous. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) - var importedName = symbolName(importedSymbol); + var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } @@ -88764,15 +90372,6 @@ var ts; return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; } FindAllReferences.getExportInfo = getExportInfo; - function symbolName(symbol) { - if (symbol.escapedName !== "default" /* Default */) { - return symbol.escapedName; - } - return ts.forEach(symbol.declarations, function (decl) { - var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ && name.escapedText; - }); - } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. @@ -88847,9 +90446,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 270 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + var result_5 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); + return result_5; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -88882,8 +90481,8 @@ var ts; case "symbol": { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_3 = def.node; @@ -88891,13 +90490,13 @@ var ts; } case "keyword": { var node_4 = def.node; - var name_5 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; + var name_4 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } case "this": { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { @@ -89010,7 +90609,7 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -89025,32 +90624,36 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } - if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { - return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet); + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + node = undefined; } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function isModuleReferenceLocation(node) { - if (!ts.isStringLiteralLike(node)) { - return false; - } - switch (node.parent.kind) { - case 238 /* ModuleDeclaration */: - case 253 /* ExternalModuleReference */: - case 243 /* ImportDeclaration */: - case 249 /* ExportDeclaration */: - return true; - case 186 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent); - default: - return false; - } + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile); } - function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) { + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); - var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. return { type: "node", node: reference.literal }; } else { @@ -89073,10 +90676,11 @@ var ts; } break; default: + // This may be merged with something. ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; + return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -89104,17 +90708,17 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; - var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); - if (node.kind === 79 /* DefaultKeyword */) { + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + if (node && node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -89160,7 +90764,6 @@ var ts; return ts.firstDefined(symbol.declarations, function (decl) { if (!decl.parent) { // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. - ts.Debug.assert(decl.kind === 273 /* SourceFile */); ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol)); } return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) @@ -89234,7 +90837,7 @@ var ts; // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** @@ -89278,10 +90881,8 @@ var ts; var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; - // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - if (!(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) { + if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); - } } } // For each import, find all references to that import in its source file. @@ -89310,6 +90911,17 @@ var ts; } } } + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -89333,22 +90945,14 @@ var ts; var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */); if (bindingElement && bindingElement.parent.kind === 179 /* ObjectBindingPattern */ && + ts.isIdentifier(bindingElement.name) && !bindingElement.propertyName) { return bindingElement; } } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - if (!bindingElement) - return undefined; - var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { - // See GH#16922 - ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); - return propSymbol.target; - } - return propSymbol; + return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); } /** * Determines the smallest scope in which a symbol may have named references. @@ -89519,6 +91123,9 @@ var ts; getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } + function hasMatchingMeaning(referenceLocation, state) { + return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (!isValidReferencePosition(referenceLocation, search.text)) { @@ -89534,9 +91141,8 @@ var ts; } return; } - if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) { + if (!hasMatchingMeaning(referenceLocation, state)) return; - } var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); if (!referenceSymbol) { return; @@ -90197,7 +91803,9 @@ var ts; var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. - return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) + return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) || + // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); }) ? [sigInfo] : [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node)); } @@ -90252,14 +91860,14 @@ var ts; function getReferenceAtPosition(sourceFile, position, program) { var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { - var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); - return file && { fileName: referencePath.fileName, file: file }; + var file_16 = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file_16 && { fileName: referencePath.fileName, file: file_16 }; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - var file = reference && program.getSourceFile(reference.resolvedFileName); - return file && { fileName: typeReferenceDirective.fileName, file: file }; + var file_17 = reference && program.getSourceFile(reference.resolvedFileName); + return file_17 && { fileName: typeReferenceDirective.fileName, file: file_17 }; } return undefined; } @@ -90431,6 +92039,7 @@ var ts; "author", "argument", "borrows", + "callback", "class", "constant", "constructor", @@ -90495,10 +92104,12 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 293 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: + case 297 /* JSDocPropertyTag */: return [declaration]; - case 292 /* JSDocTypedefTag */: - return [declaration.parent]; + case 291 /* JSDocCallbackTag */: + case 296 /* JSDocTypedefTag */: + return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); } @@ -90518,15 +92129,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 286 /* JSDocAugmentsTag */: + case 289 /* JSDocAugmentsTag */: return withNode(tag.class); - case 291 /* JSDocTemplateTag */: + case 295 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 290 /* JSDocTypeTag */: + case 294 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 292 /* JSDocTypedefTag */: - case 293 /* JSDocPropertyTag */: - case 288 /* JSDocParameterTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: + case 297 /* JSDocPropertyTag */: + case 292 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -90851,12 +92463,42 @@ var ts; JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ JsTyping.nodeCoreModuleList = [ - "buffer", "querystring", "events", "http", "cluster", - "zlib", "os", "https", "punycode", "repl", "readline", - "vm", "child_process", "url", "dns", "net", - "dgram", "fs", "path", "string_decoder", "tls", - "crypto", "stream", "util", "assert", "tty", "domain", - "constants", "process", "v8", "timers", "console" + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" ]; /* @internal */ JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); @@ -90915,8 +92557,8 @@ var ts; getTypingNamesFromSourceFileNames(fileNames); // add typings for unresolved imports if (unresolvedImports) { - var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); - addInferredTypings(module, "Inferred typings from unresolved imports"); + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); } // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach(function (typing, name) { @@ -91013,8 +92655,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -91114,7 +92756,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_12 = function (sourceFile) { + var _loop_14 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -91124,9 +92766,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; - _loop_12(sourceFile); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + _loop_14(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -91503,7 +93145,7 @@ var ts; if (ts.hasJSDocNodes(node)) { ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 292 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(tag)) { addLeafNode(tag); } }); @@ -91578,6 +93220,7 @@ var ts; } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { + var _a; target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); if (source.additionalNodes) { @@ -91588,7 +93231,6 @@ var ts; mergeChildren(target.children); sortChildren(target.children); } - var _a; } /** Recursively ensure that each NavNode's children are in sorted order. */ function sortChildren(children) { @@ -91616,8 +93258,6 @@ var ts; case 192 /* ArrowFunction */: case 204 /* ClassExpression */: return getFunctionOrClassName(node); - case 292 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return undefined; } @@ -91659,29 +93299,10 @@ var ts; return "()"; case 159 /* IndexSignature */: return "[]"; - case 292 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return ""; } } - function getJSDocTypedefTagName(node) { - if (node.name) { - return node.name.text; - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 213 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71 /* Identifier */) { - return nameIdentifier.text; - } - } - } - return ""; - } - } /** Flattens the NavNode tree to a list, keeping only the top-level items. */ function topLevelItems(root) { var topLevel = []; @@ -91707,7 +93328,8 @@ var ts; case 238 /* ModuleDeclaration */: case 273 /* SourceFile */: case 236 /* TypeAliasDeclaration */: - case 292 /* JSDocTypedefTag */: + case 296 /* JSDocTypedefTag */: + case 291 /* JSDocCallbackTag */: return true; case 154 /* Constructor */: case 153 /* MethodDeclaration */: @@ -91870,17 +93492,23 @@ var ts; */ function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(topLevelImportDecls); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; var ambientModuleBody = getModuleBlock(ambientModule); var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(ambientModuleImportDecls); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); - function organizeImportsWorker(oldImportDecls) { + function organizeImportsWorker(oldImportDecls, coalesce) { if (ts.length(oldImportDecls) === 0) { return; } @@ -91894,7 +93522,7 @@ var ts; var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + ? coalesce(importGroup) : importGroup; }); // Delete or replace the first import. @@ -91969,7 +93597,9 @@ var ts; } } function getExternalModuleName(specifier) { - return ts.isStringLiteralLike(specifier) ? specifier.text : undefined; + return specifier !== undefined && ts.isStringLiteralLike(specifier) + ? specifier.text + : undefined; } /* @internal */ // Internal for testing /** @@ -92015,15 +93645,14 @@ var ts; } } newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); - var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { - return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || - compareIdentifiers(s1.name, s2.name); - }); + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); @@ -92069,23 +93698,77 @@ var ts; namedImports: namedImports, }; } - function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); - } } OrganizeImports.coalesceImports = coalesceImports; + /* @internal */ // Internal for testing + /** + * @param exportGroup a list of ExportDeclarations, all with the same module name. + */ + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + /* + * Returns entire export declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + */ + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + // Only the first such export is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); + } /* internal */ // Exported for testing function compareModuleSpecifiers(m1, m2) { var name1 = getExternalModuleName(m1); var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); /* @internal */ @@ -92095,7 +93778,7 @@ var ts; var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) { + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); if (newPath !== undefined) { @@ -92107,25 +93790,16 @@ var ts; } ts.getEditsForFileRename = getEditsForFileRename; function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var cfg = program.getCompilerOptions().configFile; - if (!cfg) - return; - var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath); + var configFile = program.getCompilerOptions().configFile; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); if (oldFile) { - changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath); + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); } } - function getFilesEntry(cfg, fileName) { - var filesProp = ts.find(cfg.properties, function (prop) { - return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; - }); - var files = filesProp && filesProp.initializer; - return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined; - } function isRef(toUpdate) { return "fileName" in toUpdate; } - function getImportsToUpdate(program, oldFilePath) { + function getImportsToUpdate(program, oldFilePath, host) { var checker = program.getTypeChecker(); var result = []; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { @@ -92141,8 +93815,10 @@ var ts; // If it resolved to something already, ignore. if (checker.getSymbolAtLocation(importStringLiteral)) continue; - var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (ts.contains(resolved.failedLookupLocations, oldFilePath)) { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); } } @@ -92151,11 +93827,11 @@ var ts; } function getPathUpdater(oldFilePath, newFilePath, host) { // Get the relative path from old to new location, and append it on to the end of imports and normalize. - var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); return function (oldPath) { if (!ts.pathIsRelative(oldPath)) return; - return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); }; } function createStringRange(node, sourceFile) { @@ -92176,7 +93852,27 @@ var ts; OutliningElementsCollector.collectElements = collectElements; function addNodeOutliningSpans(sourceFile, cancellationToken, out) { var depthRemaining = 40; - sourceFile.forEachChild(function walk(n) { + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + } + } + function visitNonImportNode(n) { if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); @@ -92189,17 +93885,17 @@ var ts; depthRemaining--; if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { // Consider an 'else if' to be on the same depth as the 'if'. - walk(n.expression); - walk(n.thenStatement); + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); depthRemaining++; - walk(n.elseStatement); + visitNonImportNode(n.elseStatement); depthRemaining--; } else { - n.forEachChild(walk); + n.forEachChild(visitNonImportNode); } depthRemaining++; - }); + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -92214,7 +93910,7 @@ var ts; } if (!result[1]) { var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); - regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region")); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region")); } else { var region = regions.pop(); @@ -92248,7 +93944,7 @@ var ts; break; case 3 /* MultiLineCommentTrivia */: combineAndAddMultipleSingleLineComments(); - out.push(createOutliningSpanFromBounds(pos, end)); + out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */)); singleLineCommentCount = 0; break; default: @@ -92259,12 +93955,12 @@ var ts; function combineAndAddMultipleSingleLineComments() { // Only outline spans of two or more consecutive single line comments if (singleLineCommentCount > 1) { - out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */)); } } } - function createOutliningSpanFromBounds(pos, end) { - return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { @@ -92298,7 +93994,7 @@ var ts; default: // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. - return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } case 239 /* ModuleBlock */: return spanForNode(n.parent); @@ -92330,14 +94026,14 @@ var ts; return undefined; } var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); - return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { if (hintSpan === void 0) { hintSpan = textSpan; } if (autoCollapse === void 0) { autoCollapse = false; } if (bannerText === void 0) { bannerText = "..."; } - return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); @@ -92620,13 +94316,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_13 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_4 = _loop_13(start); + var state_4 = _loop_15(start); if (typeof state_4 === "object") return state_4.value; } @@ -93172,6 +94868,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } + // Can't rename a module name. + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -93291,7 +94990,7 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_14 = function (declaration) { + var _loop_16 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -93305,7 +95004,7 @@ var ts; }; for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { var declaration = declarations_12[_b]; - var state_5 = _loop_14(declaration); + var state_5 = _loop_16(declaration); if (typeof state_5 === "object") return state_5.value; } @@ -93652,7 +95351,9 @@ var ts; program.getSemanticDiagnostics(sourceFile); var checker = program.getDiagnosticsProducingTypeChecker(); var diags = []; - if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))) { + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJavaScript(sourceFile); @@ -93694,16 +95395,39 @@ var ts; var name = importNameForConvertToDefaultImport(importNode); if (!name) continue; - var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); } } } - return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 213 /* VariableStatement */: + return statement.declarationList.declarations.some(function (decl) { + return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); + case 215 /* ExpressionStatement */: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + var kind = ts.getSpecialPropertyAssignmentKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } function importNameForConvertToDefaultImport(node) { switch (node.kind) { case 243 /* ImportDeclaration */: @@ -94434,7 +96158,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_15 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -94453,7 +96177,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_15(opt); + _loop_17(opt); } return options; } @@ -94857,6 +96581,7 @@ var ts; rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. @@ -95317,6 +97042,9 @@ var ts; function isArrowFunctionContext(context) { return context.contextNode.kind === 192 /* ArrowFunction */; } + function isImportTypeContext(context) { + return context.contextNode.kind === 178 /* ImportType */; + } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; } @@ -95439,18 +97167,18 @@ var ts; // This array is used only during construction of the rulesbucket in the map var rulesBucketConstructionStateList = new Array(map.length); for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { - var rule = rules_1[_i]; - var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; - for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var rule_1 = rules_1[_i]; + var specificRule = rule_1.leftTokenRange.isSpecific && rule_1.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule_1.leftTokenRange.tokens; _a < _b.length; _a++) { var left = _b[_a]; - for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + for (var _c = 0, _d = rule_1.rightTokenRange.tokens; _c < _d.length; _c++) { var right = _d[_c]; var index = getRuleBucketIndex(left, right); var rulesBucket = map[index]; if (rulesBucket === undefined) { rulesBucket = map[index] = []; } - addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); + addRule(rulesBucket, rule_1.rule, specificRule, rulesBucketConstructionStateList, index); } } } @@ -96757,7 +98485,7 @@ var ts; NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; })(NextTokenKind || (NextTokenKind = {})); function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { - var nextToken = ts.findNextToken(precedingToken, current); + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); if (!nextToken) { return 0 /* Unknown */; } @@ -96806,9 +98534,10 @@ var ts; } function getContainingList(node, sourceFile) { if (node.parent) { + var end = node.end; switch (node.parent.kind) { case 161 /* TypeReference */: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); case 183 /* ObjectLiteralExpression */: return node.parent.properties; case 182 /* ArrayLiteralExpression */: @@ -96823,22 +98552,25 @@ var ts; case 163 /* ConstructorType */: case 158 /* ConstructSignature */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || + getListIfStartEndIsInListRange(node.parent.parameters, start, end); } case 234 /* ClassDeclaration */: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); case 187 /* NewExpression */: case 186 /* CallExpression */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || + getListIfStartEndIsInListRange(node.parent.arguments, start, end); } case 232 /* VariableDeclarationList */: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); case 246 /* NamedImports */: case 250 /* NamedExports */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); + case 179 /* ObjectBindingPattern */: + case 180 /* ArrayBindingPattern */: + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); } } return undefined; @@ -97160,10 +98892,10 @@ var ts; return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { - return node.getEnd(); + return end; } - var end = node.getEnd(); var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) ? newEnd @@ -97188,7 +98920,8 @@ var ts; this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + this.newFiles = []; + this.deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map } ChangeTracker.fromContext = function (context) { @@ -97232,35 +98965,14 @@ var ts; this.deleteNode(sourceFile, node); return this; } - var id = ts.getNodeId(node); - ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); - this.deletedNodesInLists[id] = true; - if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); - if (nextToken && isSeparator(node, nextToken)) { - // find first non-whitespace position in the leading trivia of the node - var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var nextElement = containingList[index + 1]; - /// find first non-whitespace position in the leading trivia of the next node - var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node - this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - } - } - else { - var prev = containingList[index - 1]; - if (this.deletedNodesInLists[ts.getNodeId(prev)]) { - var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var end = getAdjustedEndPosition(sourceFile, node, {}); - this.deleteRange(sourceFile, { pos: pos, end: end }); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); - } - } - } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!this.deletedNodesInLists.has(node), "Deleting a node twice"); + this.deletedNodesInLists.add(node); + this.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); return this; }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { @@ -97289,10 +99001,13 @@ var ts; if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 26 /* CommaToken */ ? next : undefined; + }; ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { - return this.replaceNode(sourceFile, oldNode, newNode, { - suffix: "," + this.newLineCharacter - }); + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } @@ -97326,7 +99041,8 @@ var ts; // Otherwise, add an extra new line immediately before the error span. var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); - var text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter; + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { @@ -97399,20 +99115,38 @@ var ts; }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); - var prefix = ""; - var suffix = this.newLineCharacter; - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { - prefix = this.newLineCharacter; - // For `class C {\n}`, don't add the trailing "\n" - if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { // TODO: GH#4130 remove 'as any' - suffix = ""; - } - } var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix }); + this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { + if (cls.members.length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + // For `class C {\n}`, don't add the trailing "\n" + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + } + else { + return { prefix: "", suffix: this.newLineCharacter }; + } + } + else { + return { prefix: this.newLineCharacter, suffix: "" }; + } + }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { if (needSemicolonBetween(after, newNode)) { // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI @@ -97421,9 +99155,13 @@ var ts; } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after)); + return endPosition; }; - ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; } @@ -97468,13 +99206,16 @@ var ts; this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } }; + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); + }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, * i.e. arguments in arguments lists, parameters in parameter lists etc. * Note that separators are part of the node in statements and class elements. */ - ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { - var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); return this; @@ -97592,6 +99333,19 @@ var ts; } }); }; + ChangeTracker.prototype.finishTrailingCommaAfterDeletingNodesInList = function () { + var _this = this; + this.deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !_this.deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } + }); + }; /** * Note: after calling this, the TextChanges object must be discarded! * @param validate only for tests @@ -97600,11 +99354,24 @@ var ts; */ ChangeTracker.prototype.getChanges = function (validate) { this.finishClassesWithNodesInsertedAtStart(); - return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + this.finishTrailingCommaAfterDeletingNodesInList(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); }; return ChangeTracker; }()); textChanges_3.ChangeTracker = ChangeTracker; + // find first non-whitespace position in the leading trivia of the node + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } function getClassBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } @@ -97614,15 +99381,16 @@ var ts; return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // order changes by start position - var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); - var _loop_16 = function (i) { + // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_16(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -97631,6 +99399,11 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter) { + var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -97980,10 +99753,11 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); - function getRefactorContextLength(context) { - return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); } - ts.getRefactorContextLength = getRefactorContextLength; + ts.getRefactorContextSpan = getRefactorContextSpan; })(ts || (ts = {})); /* @internal */ var ts; @@ -98051,7 +99825,7 @@ var ts; if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { if (!decl.typeParameters) { var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); - if (typeParameters) + if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); @@ -98087,18 +99861,18 @@ var ts; } function transformJSDocType(node) { switch (node.kind) { - case 276 /* JSDocAllType */: - case 277 /* JSDocUnknownType */: + case 278 /* JSDocAllType */: + case 279 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 280 /* JSDocOptionalType */: + case 282 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 279 /* JSDocNonNullableType */: + case 281 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 278 /* JSDocNullableType */: + case 280 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 282 /* JSDocVariadicType */: + case 284 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 281 /* JSDocFunctionType */: + case 283 /* JSDocFunctionType */: return transformJSDocFunctionType(node); case 161 /* TypeReference */: return transformJSDocTypeReference(node); @@ -98122,7 +99896,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 282 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -98403,7 +100177,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -98467,7 +100241,7 @@ var ts; case 186 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); } return false; } @@ -98540,27 +100314,30 @@ var ts; changes.deleteNode(sourceFile, assignment.parent); } else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + return true; } - changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); - return changedToDefaultExport; } } else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { convertNamedExport(sourceFile, assignment, changes, exports); } return false; - var _a; } /** * Convert `module.exports = { ... }` to individual exports.. * We can't always do this if the module has interesting members -- then it will be a default export instead. */ function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { case 155 /* GetAccessor */: case 156 /* SetAccessor */: @@ -98576,6 +100353,7 @@ var ts; ts.Debug.assertNever(prop); } }); + return statements && [statements, false]; } function convertNamedExport(sourceFile, assignment, changes, exports) { // If "originalKeywordKind" was set, this is e.g. `exports. @@ -98596,30 +100374,6 @@ var ts; convertExportsPropertyAssignment(assignment, sourceFile, changes); } } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; - switch (exported.kind) { - case 191 /* FunctionExpression */: - case 192 /* ArrowFunction */: { - // `module.exports = function f() {}` --> `export default function f() {}` - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 204 /* ClassExpression */: { - // `module.exports = class C {}` --> `export default class C {}` - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 186 /* CallExpression */: - if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) { - return convertReExportAll(exported.arguments[0], checker); - } - // falls through - default: - // `module.exports = 0;` --> `export default 0;` - return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; - } - } function convertReExportAll(reExported, checker) { // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` var moduleSpecifier = reExported.text; @@ -98695,7 +100449,7 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -98706,7 +100460,7 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } @@ -98755,7 +100509,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -98797,17 +100551,9 @@ var ts; } function makeSingleImport(localName, propertyName, moduleSpecifier) { return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); } - function makeImport(name, namedImports, moduleSpecifier) { - return makeImportDeclaration(name, namedImports, moduleSpecifier); - } - function makeImportDeclaration(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier); - } - codefix.makeImportDeclaration = makeImportDeclaration; function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); } @@ -98968,7 +100714,7 @@ var ts; var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; } @@ -99014,11 +100760,11 @@ var ts; if (context.symbolToken && ts.isIdentifier(context.symbolToken)) { for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) { var declaration = existingImports_1[_i].declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); + var namespace_2 = getNamespaceImportName(declaration); + if (namespace_2) { + var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2)); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken)); } } } @@ -99085,12 +100831,6 @@ var ts; return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); } } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; - }) || false; - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -99104,274 +100844,15 @@ var ts; ts.Debug.assertNever(kind); } } - function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) { - var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(sourceFile); + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; - } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences); return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - /** - * Looks for a existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var count = 0; - for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { - count++; - } - return count; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName); - } - } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { var fromExistingImport = ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -99390,7 +100871,7 @@ var ts; var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences); + : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences); for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) { var info = newImportInfos_1[_i]; addNew.push(getCodeActionForNewImport(ctx, info)); @@ -99848,7 +101329,24 @@ var ts; /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + } + // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; } function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. @@ -100160,6 +101658,7 @@ var ts; ts.Diagnostics._0_is_declared_but_never_used.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -100170,9 +101669,13 @@ var ts; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start, /*deleted*/ undefined); }); + if (delDestructure.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined); }); if (deletion.length) { result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } @@ -100183,36 +101686,69 @@ var ts; return result; }, fixIds: [fixIdPrefix, fixIdDelete], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var sourceFile = context.sourceFile; - var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); - switch (context.fixId) { - case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); - } - break; - case fixIdDelete: - var importDecl = tryGetFullImport(diag.file, diag.start); - if (importDecl) { - changes.deleteNode(sourceFile, importDecl); - } - else { - tryDeleteDeclaration(changes, sourceFile, token); - } - break; - default: - ts.Debug.fail(JSON.stringify(context.fixId)); - } - }); }, + getAllCodeActions: function (context) { + // Track a set of deleted nodes that may be ancestors of other marked for deletion -- only delete the ancestors. + var deleted = new NodeSet(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var sourceFile = context.sourceFile; + var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: + // Ignore if this range was already deleted. + if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); })) + break; + var importDecl = tryGetFullImport(diag.file, diag.start); + if (importDecl) { + changes.deleteNode(sourceFile, importDecl); + } + else { + if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) { + tryDeleteDeclaration(changes, sourceFile, token, deleted); + } + } + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, }); // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(sourceFile, pos) { var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; } + function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) { + var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent)) + return false; + var decl = startToken.parent.parent; + switch (decl.kind) { + case 231 /* VariableDeclaration */: + tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors); + break; + case 148 /* Parameter */: + if (deletedAncestors) + deletedAncestors.add(decl); + changes.deleteNodeInList(sourceFile, decl); + break; + case 181 /* BindingElement */: + if (deletedAncestors) + deletedAncestors.add(decl); + changes.deleteNode(sourceFile, decl); + break; + default: + return ts.Debug.assertNever(decl); + } + return true; + } function getToken(sourceFile, pos) { - var token = ts.findPrecedingToken(pos, sourceFile); + var token = ts.findPrecedingToken(pos, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); // this handles var ["computed"] = 12; return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token; } @@ -100237,38 +101773,45 @@ var ts; } return false; } - function tryDeleteDeclaration(changes, sourceFile, token) { + function tryDeleteDeclaration(changes, sourceFile, token, deletedAncestors) { switch (token.kind) { case 71 /* Identifier */: - tryDeleteIdentifier(changes, sourceFile, token); + tryDeleteIdentifier(changes, sourceFile, token, deletedAncestors); break; case 151 /* PropertyDeclaration */: case 245 /* NamespaceImport */: + if (deletedAncestors) + deletedAncestors.add(token.parent); changes.deleteNode(sourceFile, token.parent); break; default: - tryDeleteDefault(changes, sourceFile, token); + tryDeleteDefault(changes, sourceFile, token, deletedAncestors); } } - function tryDeleteDefault(changes, sourceFile, token) { + function tryDeleteDefault(changes, sourceFile, token, deletedAncestors) { if (ts.isDeclarationName(token)) { + if (deletedAncestors) + deletedAncestors.add(token.parent); changes.deleteNode(sourceFile, token.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + if (deletedAncestors) + deletedAncestors.add(token.parent.parent); changes.deleteNode(sourceFile, token.parent.parent); } } - function tryDeleteIdentifier(changes, sourceFile, identifier) { + function tryDeleteIdentifier(changes, sourceFile, identifier, deletedAncestors) { var parent = identifier.parent; switch (parent.kind) { case 231 /* VariableDeclaration */: - tryDeleteVariableDeclaration(changes, sourceFile, parent); + tryDeleteVariableDeclaration(changes, sourceFile, parent, deletedAncestors); break; case 147 /* TypeParameter */: - var typeParameters = parent.parent.typeParameters; + var typeParameters = ts.getEffectiveTypeParameterDeclarations(parent.parent); if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; + var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, end, /*includeJsDocComment*/ false); ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); changes.deleteNodeRange(sourceFile, previousToken, nextToken); @@ -100299,6 +101842,20 @@ var ts; changes.deleteNodeInList(sourceFile, parent); } break; + case 181 /* BindingElement */: { + var pattern = parent.parent; + switch (pattern.kind) { + case 180 /* ArrayBindingPattern */: + changes.deleteNode(sourceFile, parent); // Don't delete ',' + break; + case 179 /* ObjectBindingPattern */: + changes.deleteNodeInList(sourceFile, parent); + break; + default: + return ts.Debug.assertNever(pattern); + } + break; + } // handle case where 'import a = A;' case 242 /* ImportEqualsDeclaration */: var importEquals = ts.getAncestor(identifier, 242 /* ImportEqualsDeclaration */); @@ -100337,7 +101894,7 @@ var ts; tryDeleteNamedImportBinding(changes, sourceFile, parent); break; default: - tryDeleteDefault(changes, sourceFile, identifier); + tryDeleteDefault(changes, sourceFile, identifier, deletedAncestors); break; } } @@ -100360,15 +101917,19 @@ var ts; } } // token.parent is a variableDeclaration - function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { + function tryDeleteVariableDeclaration(changes, sourceFile, varDecl, deletedAncestors) { switch (varDecl.parent.parent.kind) { case 219 /* ForStatement */: { var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; if (forInitializer.declarations.length === 1) { + if (deletedAncestors) + deletedAncestors.add(forInitializer); changes.deleteNode(sourceFile, forInitializer); } else { + if (deletedAncestors) + deletedAncestors.add(varDecl); changes.deleteNodeInList(sourceFile, varDecl); } break; @@ -100377,6 +101938,8 @@ var ts; var forOfStatement = varDecl.parent.parent; ts.Debug.assert(forOfStatement.initializer.kind === 232 /* VariableDeclarationList */); var forOfInitializer = forOfStatement.initializer; + if (deletedAncestors) + deletedAncestors.add(forOfInitializer.declarations[0]); changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); break; case 220 /* ForInStatement */: @@ -100385,13 +101948,131 @@ var ts; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { + if (deletedAncestors) + deletedAncestors.add(variableStatement); changes.deleteNode(sourceFile, variableStatement); } else { + if (deletedAncestors) + deletedAncestors.add(varDecl); changes.deleteNodeInList(sourceFile, varDecl); } } } + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + switch (container.kind) { + case 216 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + break; + } + // falls through + case 218 /* WhileStatement */: + case 219 /* ForStatement */: + changes.deleteNode(sourceFile, container); + break; + default: + if (ts.isBlock(statement.parent)) { + split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); + } + else { + changes.deleteNode(sourceFile, statement); + } + } + } + function shouldRemove(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 235 /* InterfaceDeclaration */: + case 236 /* TypeAliasDeclaration */: + return true; + case 238 /* ModuleDeclaration */: + return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; + case 237 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + } + } + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + ts.Debug.assert(index !== -1); + return arr.slice(index); + } + // Calls 'cb' with the start and end of each range where 'pred' is true. + function split(arr, pred, cb) { + ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -100413,7 +102094,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 278 /* JSDocNullableType */) { + if (typeNode.kind === 280 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -100433,7 +102114,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 278 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; + var fixedType = typeNode.kind === 280 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -100811,16 +102492,16 @@ var ts; } var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var seenFunctions = ts.createMap(); + var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, markSeen); }); }, }); @@ -100834,7 +102515,7 @@ var ts; return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { return undefined; } @@ -100843,17 +102524,18 @@ var ts; // Variable and Property declarations case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) { + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); return symbol.valueDeclaration; } + return undefined; } } var containingFunction = ts.getContainingFunction(token); @@ -100869,7 +102551,7 @@ var ts; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { + if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); return param; @@ -101061,6 +102743,16 @@ var ts; case 185 /* ElementAccessExpression */: inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); break; + case 231 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through default: return inferTypeFromContextualType(node, checker, usageContext); } @@ -101232,7 +102924,7 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); + return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); @@ -101349,7 +103041,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -101506,6 +103198,290 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +// Used by importFixes to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + // For each symlink/original for a module, returns a list of ways to import that file. + function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var compilerOptions = program.getCompilerOptions(); + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName); + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + // For a type definition, we can strip `/index` even with classic resolution. + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName)); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -101575,7 +103551,40 @@ var ts; } } function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + ts.Debug.assert(token.kind === 91 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 178 /* ImportType */); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + changes.replaceNode(sourceFile, importType, newTypeNode); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -101593,7 +103602,7 @@ var ts; * Exported for tests. */ function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -101662,7 +103671,7 @@ var ts; extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); if (parsedFunctionIndexMatch) { @@ -102774,8 +104783,8 @@ var ts; i_1++; } // Note that we add the current node's type parameters *after* updating the corresponding scope. - if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { - for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { var typeParameterDecl = _b[_a]; var typeParameter = checker.getTypeAtLocation(typeParameterDecl); if (allTypeParameterUsages.has(typeParameter.id.toString())) { @@ -102797,7 +104806,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_17 = function (i) { + var _loop_19 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -102837,21 +104846,11 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_17(i); + _loop_19(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; - function hasTypeParameters(node) { - return ts.isDeclarationWithTypeParameters(node) && - node.typeParameters !== undefined && - node.typeParameters.length > 0; - } function isInGenericContext(node) { - for (; node; node = node.parent) { - if (hasTypeParameters(node)) { - return true; - } - } - return false; + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); } function recordTypeParameterUsages(type) { // PERF: This is potentially very expensive. `type` could be a library type with @@ -103116,8 +105115,8 @@ var ts; var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { - var file = context.file, startPosition = context.startPosition; - if (!getConvertibleFieldAtPosition(file, startPosition)) + var file = context.file; + if (!getConvertibleFieldAtPosition(context, file)) return undefined; return [{ name: actionName, @@ -103131,27 +105130,46 @@ var ts; }]; } function getEditsForAction(context, _actionName) { - var file = context.file, startPosition = context.startPosition; - var fieldInfo = getConvertibleFieldAtPosition(file, startPosition); + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context, file); if (!fieldInfo) return undefined; var isJS = ts.isSourceFileJavaScript(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration; + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); var isInClassLike = ts.isClassLike(container); + // avoid Readonly modifier because it will convert to get accessor + var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; var accessorModifiers = isInClassLike - ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 /* Private */ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) : declaration.modifiers + ? !modifierFlags || modifierFlags & 8 /* Private */ + ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined; var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined; - updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container); + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); - var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); insertAccessor(changeTracker, file, getAccessor, declaration, container); - insertAccessor(changeTracker, file, setAccessor, declaration, container); + if (isReadonly) { + // readonly modifier only existed in classLikeDeclaration + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } var edits = changeTracker.getChanges(); var renameFilename = file.fileName; - var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1; - var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false); + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function isConvertableName(name) { @@ -103171,24 +105189,32 @@ var ts; var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined); return modifiers && ts.createNodeArray(modifiers); } - function getConvertibleFieldAtPosition(file, startPosition) { + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + function getConvertibleFieldAtPosition(context, file) { + var startPosition = context.startPosition, endPosition = context.endPosition; var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); - // make sure propertyDeclaration have AccessibilityModifier or Static Modifier - var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */; - if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier + var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) + || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; - var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name); - var accessorName = createPropertyName(declaration.name.text, declaration.name); - ts.suppressLeadingAndTrailingTrivia(fieldName); - ts.suppressLeadingAndTrailingTrivia(declaration); + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file.text), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file.text) : name, declaration.name); return { isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), container: declaration.kind === 148 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name, declaration: declaration, fieldName: fieldName, accessorName: accessorName, + renameAccessor: startWithUnderscore }; } function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { @@ -103212,16 +105238,11 @@ var ts; var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } - function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) { - var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer); - changeTracker.insertNodeAtClassStart(file, classLikeContainer, property); - changeTracker.deleteNodeInList(file, declaration); - } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); changeTracker.replacePropertyAssignment(file, declaration, assignment); } - function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) { + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { if (ts.isPropertyDeclaration(declaration)) { updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); } @@ -103229,19 +105250,636 @@ var ts; updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container); + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { ts.isParameterPropertyDeclaration(declaration) ? changeTracker.insertNodeAtClassStart(file, container, accessor) - : changeTracker.insertNodeAfter(file, declaration, accessor); + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + if (!constructor.body) + return; + var file = context.file, program = context.program, cancellationToken = context.cancellationToken; + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); }); + ts.forEach(referenceEntries, function (entry) { + var parent = entry.parent; + var accessorName = ts.createIdentifier(fieldName.text); + var node = ts.isBinaryExpression(parent) + ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) + : ts.isPropertyAccessExpression(parent) + ? ts.updatePropertyAccess(parent, parent.expression, accessorName) + : ts.Debug.fail("Unexpected write access token"); + changeTracker.replaceNode(file, parent, node); + }); } })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + return undefined; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getFirstAndLastStatementToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + // Can't only partially include the start node or be partially into the next node + if (range.pos > statements[startNodeIndex].getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + // Can't be partially into the next node + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + } + function doChange(oldFile, program, toMove, changes, host) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + // If previous file was global, this is easy. + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. + function getStatementsToMove(context) { + var statements = context.file.statements; + var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var all = []; + var ranges = []; + var rangeToMove = statements.slice(first, afterLast); + ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { + for (var i = start; i < afterEnd; i++) + all.push(rangeToMove[i]); + ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); + }); + return { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 243 /* ImportDeclaration */: + return true; + case 242 /* ImportEqualsDeclaration */: + return !ts.hasModifier(node, 1 /* Export */); + case 213 /* VariableStatement */: + return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + if (importsFromNewFile) { + changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last; + changes.deleteNodeRange(sourceFile, first_1, last_3); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_20 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_21 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_21(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_20(sourceFile); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 243 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 242 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path); + } + else { + ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. + var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2 /* Const */; } + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 243 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 242 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.deleteNode(sourceFile, importDecl); + } + break; + case 231 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 245 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.deleteNode(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.deleteNode(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.deleteNode(sourceFile, namedBindings); + } + else if (namedBindings.kind === 246 /* NamedImports */) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.deleteNodeInList(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 71 /* Identifier */: + if (isUnused(name)) { + changes.deleteNode(sourceFile, name); + } + break; + case 180 /* ArrayBindingPattern */: + break; + case 179 /* ObjectBindingPattern */: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.deleteNode(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.deleteNode(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512 /* Default */)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + // Below should all be utilities + function isInImport(decl) { + switch (decl.kind) { + case 242 /* ImportEqualsDeclaration */: + case 247 /* ImportSpecifier */: + case 244 /* ImportClause */: + return true; + case 231 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 181 /* BindingElement */: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 243 /* ImportDeclaration */: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 242 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : undefined; + case 231 /* VariableDeclaration */: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 245 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 71 /* Identifier */: + return keep(name) ? name : undefined; + case 180 /* ArrayBindingPattern */: + return name; + case 179 /* ObjectBindingPattern */: { + // We can't handle nested destructurings or property names well here, so just copy them all. + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = /** @class */ (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 233 /* FunctionDeclaration */: + case 234 /* ClassDeclaration */: + case 238 /* ModuleDeclaration */: + case 237 /* EnumDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 242 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 233 /* FunctionDeclaration */: + case 234 /* ClassDeclaration */: + case 238 /* ModuleDeclaration */: + case 237 /* EnumDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 242 /* ImportEqualsDeclaration */: + return cb(statement); + case 213 /* VariableStatement */: + return ts.forEach(statement.declarationList.declarations, cb); + case 215 /* ExpressionStatement */: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + ? cb(statement) + : undefined; + } + } + } + function nameOfTopLevelDeclaration(d) { + return d.kind === 215 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + return ts.isVariableDeclaration(d) ? d.parent.parent : d; + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); + switch (d.kind) { + case 233 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 234 /* ClassDeclaration */: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 213 /* VariableStatement */: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 238 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 237 /* EnumDeclaration */: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 236 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 235 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 242 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 215 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 233 /* FunctionDeclaration */: + case 234 /* ClassDeclaration */: + return [decl.name.text]; + case 213 /* VariableStatement */: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 238 /* ModuleDeclaration */: + case 237 /* EnumDeclaration */: + case 236 /* TypeAliasDeclaration */: + case 235 /* InterfaceDeclaration */: + case 242 /* ImportEqualsDeclaration */: + return undefined; + case 215 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + ts.Debug.assertNever(decl); + } + } + /** Creates `exports.x = x;` */ + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var sourcemaps; (function (sourcemaps) { @@ -103563,7 +106201,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 275 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 277 /* FirstJSDocNode */ || kid.kind > 297 /* LastJSDocNode */; }); return child.kind < 145 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -103633,7 +106271,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(298 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -104156,6 +106794,9 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -104185,9 +106826,18 @@ var ts; return ts.isString(info) ? undefined : info; }; HostCache.prototype.getRootFileNames = function () { - return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { - return ts.isString(entry) ? entry : entry.hostFileName; + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6 /* JSON */) { + names.push(entry.hostFileName); + } + } }); + return names; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); @@ -104363,6 +107013,7 @@ var ts; } ts.createSourceFileLikeCache = createSourceFileLikeCache; function createLanguageService(host, documentRegistry, syntaxOnly) { + var _a; if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } if (syntaxOnly === void 0) { syntaxOnly = false; } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -104466,7 +107117,14 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: hostCache.getProjectReferences() + }; + program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; @@ -104670,6 +107328,11 @@ var ts; } return checker.getSymbolAtLocation(node); } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); + return file.getLineAndCharacterOfPosition(position); + } // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/gm; var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; @@ -104741,27 +107404,28 @@ var ts; } function makeGetTargetOfMappedPosition(extract, create) { return getTargetOfMappedPosition; - function getTargetOfMappedPosition(input) { + function getTargetOfMappedPosition(input, original) { + if (original === void 0) { original = input; } var info = extract(input); if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { - var file = program.getSourceFile(info.fileName); - if (!file) { + var file_18 = program.getSourceFile(info.fileName); + if (!file_18) { var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); - file = sourcemappedFileCache.get(path); + file_18 = sourcemappedFileCache.get(path); } - if (!file) { + if (!file_18) { return input; } - var mapper = getSourceMapper(info.fileName, file); + var mapper = getSourceMapper(info.fileName, file_18); var newLoc = mapper.getOriginalPosition(info); if (newLoc === info) return input; - return getTargetOfMappedPosition(create(newLoc, input)); + return getTargetOfMappedPosition(create(newLoc, input, original), original); } return input; } } - var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ + var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({ containerKind: info.containerKind, containerName: info.containerName, fileName: newLoc.fileName, @@ -104770,10 +107434,12 @@ var ts; textSpan: { start: newLoc.position, length: info.textSpan.length - } + }, + originalFileName: original.fileName, + originalTextSpan: original.textSpan }); }); function getTargetOfMappedDeclarationFiles(infos) { - return ts.map(infos, getTargetOfMappedDeclarationInfo); + return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); }); } /// Goto definition function getDefinitionAtPosition(fileName, position) { @@ -104806,10 +107472,12 @@ var ts; textSpan: { start: newLoc.position, length: info.textSpan.length - } + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan }); }); function getTargetOfMappedImplementationLocations(infos) { - return ts.map(infos, getTargetOfMappedImplementationLocation); + return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); }); } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); @@ -105317,8 +107985,8 @@ var ts; getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: toLineColumnOffset }; - var _a; } ts.createLanguageService = createLanguageService; /* @internal */ @@ -105389,20 +108057,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_6 = []; + var result_7 = []; var symbol = type.getProperty(name); if (type.flags & 131072 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_7.push(symbol); } }); - return result_6; + return result_7; } if (symbol) { - result_6.push(symbol); - return result_6; + result_7.push(symbol); + return result_7; } } return undefined; @@ -105469,7 +108137,7 @@ var ts; return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { - return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { @@ -105484,7 +108152,7 @@ var ts; return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } function spanInNextNode(node) { - return spanInNode(ts.findNextToken(node, node.parent)); + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); } function spanInNode(node) { if (node) { @@ -106823,5 +109491,3 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = ts.versionMajorMinor; - -//# sourceMappingURL=typescriptServices.js.map diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index a273ff745f7..ab3cb0310f4 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -34,564 +34,18 @@ var __extends = (this && this.__extends) || (function () { })(); var ts; (function (ts) { - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); - var SyntaxKind; - (function (SyntaxKind) { - SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; - SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; - SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; - SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; - SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; - SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; - SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; - SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; - SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; - SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; - SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; - SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; - SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; - SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; - SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; - SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; - SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 142] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 143] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 144] = "OfKeyword"; - SyntaxKind[SyntaxKind["QualifiedName"] = 145] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 146] = "ComputedPropertyName"; - SyntaxKind[SyntaxKind["TypeParameter"] = 147] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 148] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 149] = "Decorator"; - SyntaxKind[SyntaxKind["PropertySignature"] = 150] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 151] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 152] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 153] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 154] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 155] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 156] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 157] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 158] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 159] = "IndexSignature"; - SyntaxKind[SyntaxKind["TypePredicate"] = 160] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 161] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 162] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 163] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 164] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 165] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 166] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 167] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 168] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 169] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 170] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 171] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 172] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 173] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 174] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 175] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 176] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 177] = "LiteralType"; - SyntaxKind[SyntaxKind["ImportType"] = 178] = "ImportType"; - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 179] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 180] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 181] = "BindingElement"; - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 182] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 183] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 184] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 185] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 186] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 187] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 188] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 189] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 190] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 191] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 192] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 193] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 194] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 195] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 196] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 197] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 198] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 199] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 200] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 201] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 202] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 203] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 204] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 205] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 206] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 207] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 208] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 209] = "MetaProperty"; - SyntaxKind[SyntaxKind["TemplateSpan"] = 210] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 211] = "SemicolonClassElement"; - SyntaxKind[SyntaxKind["Block"] = 212] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 213] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 214] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 215] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 216] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 217] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 218] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 219] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 220] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 221] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 222] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 223] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 224] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 225] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 226] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 227] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 228] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 229] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 230] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 231] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 232] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 233] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 234] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 235] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 236] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 237] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 238] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 239] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 240] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 241] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 242] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 243] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 244] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 245] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 246] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 247] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 248] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 249] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 250] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 251] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 252] = "MissingDeclaration"; - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 253] = "ExternalModuleReference"; - SyntaxKind[SyntaxKind["JsxElement"] = 254] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 255] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 256] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 257] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 258] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 259] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 260] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 261] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 262] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 263] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 264] = "JsxExpression"; - SyntaxKind[SyntaxKind["CaseClause"] = 265] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 266] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 267] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 268] = "CatchClause"; - SyntaxKind[SyntaxKind["PropertyAssignment"] = 269] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 270] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 271] = "SpreadAssignment"; - SyntaxKind[SyntaxKind["EnumMember"] = 272] = "EnumMember"; - SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle"; - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType"; - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; - SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 144] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 160] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 178] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; - SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 144] = "LastToken"; - SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; - SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; - SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode"; - SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; - SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword"; - })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); - var NodeFlags; - (function (NodeFlags) { - NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Let"] = 1] = "Let"; - NodeFlags[NodeFlags["Const"] = 2] = "Const"; - NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; - NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; - NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; - NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; - NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; - NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; - NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; - NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; - NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; - NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; - NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; - NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; - NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; - NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; - NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; - NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; - NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta"; - NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; - NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; - NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; - NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; - NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; - NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; - NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags"; - NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; - NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags"; - })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); - var ModifierFlags; - (function (ModifierFlags) { - ModifierFlags[ModifierFlags["None"] = 0] = "None"; - ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; - ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; - ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; - ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; - ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; - ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; - ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; - ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; - ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; - ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; - ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; - ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; - ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; - ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; - ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 3071] = "All"; - })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); - var JsxFlags; - (function (JsxFlags) { - JsxFlags[JsxFlags["None"] = 0] = "None"; - JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; - JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; - JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; - })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); - var RelationComparisonResult; - (function (RelationComparisonResult) { - RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; - RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; - RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; - })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); - var GeneratedIdentifierFlags; - (function (GeneratedIdentifierFlags) { - GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel"; - })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); - var TokenFlags; - (function (TokenFlags) { - TokenFlags[TokenFlags["None"] = 0] = "None"; - TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; - TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; - TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; - TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; - TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; - TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; - TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; - TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; - TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; - TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; - TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; - TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; - })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); - var FlowFlags; - (function (FlowFlags) { - FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; - FlowFlags[FlowFlags["Start"] = 2] = "Start"; - FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; - FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; - FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; - FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; - FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; - FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; - FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; - FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; - FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; - FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; - FlowFlags[FlowFlags["Label"] = 12] = "Label"; - FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; - })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; - var StructureIsReused; - (function (StructureIsReused) { - StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; - StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; - StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; - })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); - var UnionReduction; - (function (UnionReduction) { - UnionReduction[UnionReduction["None"] = 0] = "None"; - UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; - UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; - })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); - var NodeBuilderFlags; - (function (NodeBuilderFlags) { - NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; - NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; - NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; - NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; - NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; - NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; - NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; - NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; - NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; - NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; - NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; - })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); - var TypeFormatFlags; - (function (TypeFormatFlags) { - TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; - })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); - var SymbolFormatFlags; - (function (SymbolFormatFlags) { - SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; - SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; - SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; - SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; - SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; - })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); - var SymbolAccessibility; - (function (SymbolAccessibility) { - SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; - SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; - SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; - })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); - var SyntheticSymbolKind; - (function (SyntheticSymbolKind) { - SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; - SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; - })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); - var TypePredicateKind; - (function (TypePredicateKind) { - TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; - TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; - })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -606,269 +60,6 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var SymbolFlags; - (function (SymbolFlags) { - SymbolFlags[SymbolFlags["None"] = 0] = "None"; - SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; - SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; - SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; - SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; - SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; - SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; - SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; - SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; - SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; - SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; - SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; - SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; - SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; - SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; - SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; - SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; - SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; - SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; - SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; - SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; - SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; - SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; - SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; - SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; - SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; - SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; - SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; - SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; - SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; - SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; - SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; - SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; - SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; - SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; - SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; - SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; - SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; - SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; - SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; - SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; - SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; - SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; - SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; - SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; - SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; - SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; - SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; - })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); - var EnumKind; - (function (EnumKind) { - EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; - EnumKind[EnumKind["Literal"] = 1] = "Literal"; - })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); - var CheckFlags; - (function (CheckFlags) { - CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; - CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; - CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; - CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; - CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; - CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; - CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; - CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; - CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; - CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; - CheckFlags[CheckFlags["Late"] = 1024] = "Late"; - CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; - })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); - var InternalSymbolName; - (function (InternalSymbolName) { - InternalSymbolName["Call"] = "__call"; - InternalSymbolName["Constructor"] = "__constructor"; - InternalSymbolName["New"] = "__new"; - InternalSymbolName["Index"] = "__index"; - InternalSymbolName["ExportStar"] = "__export"; - InternalSymbolName["Global"] = "__global"; - InternalSymbolName["Missing"] = "__missing"; - InternalSymbolName["Type"] = "__type"; - InternalSymbolName["Object"] = "__object"; - InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; - InternalSymbolName["Class"] = "__class"; - InternalSymbolName["Function"] = "__function"; - InternalSymbolName["Computed"] = "__computed"; - InternalSymbolName["Resolving"] = "__resolving__"; - InternalSymbolName["ExportEquals"] = "export="; - InternalSymbolName["Default"] = "default"; - })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); - var NodeCheckFlags; - (function (NodeCheckFlags) { - NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; - NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; - NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; - NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; - NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; - NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; - NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; - NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; - NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; - NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; - NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; - })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); - var TypeFlags; - (function (TypeFlags) { - TypeFlags[TypeFlags["Any"] = 1] = "Any"; - TypeFlags[TypeFlags["String"] = 2] = "String"; - TypeFlags[TypeFlags["Number"] = 4] = "Number"; - TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; - TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["UniqueESSymbol"] = 1024] = "UniqueESSymbol"; - TypeFlags[TypeFlags["Void"] = 2048] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 8192] = "Null"; - TypeFlags[TypeFlags["Never"] = 16384] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 65536] = "Object"; - TypeFlags[TypeFlags["Union"] = 131072] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 524288] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess"; - TypeFlags[TypeFlags["Conditional"] = 2097152] = "Conditional"; - TypeFlags[TypeFlags["Substitution"] = 4194304] = "Substitution"; - TypeFlags[TypeFlags["FreshLiteral"] = 8388608] = "FreshLiteral"; - TypeFlags[TypeFlags["ContainsWideningType"] = 16777216] = "ContainsWideningType"; - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 33554432] = "ContainsObjectLiteral"; - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive"; - TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType"; - TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 13536] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; - TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique"; - TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy"; - TypeFlags[TypeFlags["Intrinsic"] = 134249103] = "Intrinsic"; - TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike"; - TypeFlags[TypeFlags["VoidLike"] = 6144] = "VoidLike"; - TypeFlags[TypeFlags["DisjointDomains"] = 134233854] = "DisjointDomains"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType"; - TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable"; - TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 7372800] = "InstantiableNonPrimitive"; - TypeFlags[TypeFlags["InstantiablePrimitive"] = 524288] = "InstantiablePrimitive"; - TypeFlags[TypeFlags["Instantiable"] = 7897088] = "Instantiable"; - TypeFlags[TypeFlags["StructuredOrInstantiable"] = 8355840] = "StructuredOrInstantiable"; - TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit"; - TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening"; - TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags"; - TypeFlags[TypeFlags["NonWideningType"] = 16777216] = "NonWideningType"; - TypeFlags[TypeFlags["Wildcard"] = 33554432] = "Wildcard"; - TypeFlags[TypeFlags["EmptyObject"] = 67108864] = "EmptyObject"; - TypeFlags[TypeFlags["ConstructionFlags"] = 117440512] = "ConstructionFlags"; - })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); - var ObjectFlags; - (function (ObjectFlags) { - ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; - ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; - ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; - ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; - ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; - ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; - ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; - ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; - ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; - ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; - })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); - var Variance; - (function (Variance) { - Variance[Variance["Invariant"] = 0] = "Invariant"; - Variance[Variance["Covariant"] = 1] = "Covariant"; - Variance[Variance["Contravariant"] = 2] = "Contravariant"; - Variance[Variance["Bivariant"] = 3] = "Bivariant"; - Variance[Variance["Independent"] = 4] = "Independent"; - })(Variance = ts.Variance || (ts.Variance = {})); - var SignatureKind; - (function (SignatureKind) { - SignatureKind[SignatureKind["Call"] = 0] = "Call"; - SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; - })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); - var IndexKind; - (function (IndexKind) { - IndexKind[IndexKind["String"] = 0] = "String"; - IndexKind[IndexKind["Number"] = 1] = "Number"; - })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); - var InferencePriority; - (function (InferencePriority) { - InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination"; - })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); - var InferenceFlags; - (function (InferenceFlags) { - InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; - })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); - var Ternary; - (function (Ternary) { - Ternary[Ternary["False"] = 0] = "False"; - Ternary[Ternary["Maybe"] = 1] = "Maybe"; - Ternary[Ternary["True"] = -1] = "True"; - })(Ternary = ts.Ternary || (ts.Ternary = {})); - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -897,390 +88,6 @@ var ts; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); - var JsxEmit; - (function (JsxEmit) { - JsxEmit[JsxEmit["None"] = 0] = "None"; - JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; - JsxEmit[JsxEmit["React"] = 2] = "React"; - JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; - })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); - var NewLineKind; - (function (NewLineKind) { - NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; - NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; - })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); - var ScriptKind; - (function (ScriptKind) { - ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; - ScriptKind[ScriptKind["JS"] = 1] = "JS"; - ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; - ScriptKind[ScriptKind["TS"] = 3] = "TS"; - ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; - ScriptKind[ScriptKind["External"] = 5] = "External"; - ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; - })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); - var ScriptTarget; - (function (ScriptTarget) { - ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; - ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; - ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; - ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; - ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; - ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; - ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; - ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; - })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); - var LanguageVariant; - (function (LanguageVariant) { - LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; - LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; - })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); - var WatchDirectoryFlags; - (function (WatchDirectoryFlags) { - WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; - WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; - })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); - var CharacterCodes; - (function (CharacterCodes) { - CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; - CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; - CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; - CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; - CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; - CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; - CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; - CharacterCodes[CharacterCodes["space"] = 32] = "space"; - CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; - CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; - CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; - CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; - CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; - CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; - CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; - CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; - CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; - CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; - CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; - CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; - CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; - CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; - CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; - CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; - CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; - CharacterCodes[CharacterCodes["_"] = 95] = "_"; - CharacterCodes[CharacterCodes["$"] = 36] = "$"; - CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; - CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; - CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; - CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; - CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; - CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; - CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; - CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; - CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; - CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; - CharacterCodes[CharacterCodes["a"] = 97] = "a"; - CharacterCodes[CharacterCodes["b"] = 98] = "b"; - CharacterCodes[CharacterCodes["c"] = 99] = "c"; - CharacterCodes[CharacterCodes["d"] = 100] = "d"; - CharacterCodes[CharacterCodes["e"] = 101] = "e"; - CharacterCodes[CharacterCodes["f"] = 102] = "f"; - CharacterCodes[CharacterCodes["g"] = 103] = "g"; - CharacterCodes[CharacterCodes["h"] = 104] = "h"; - CharacterCodes[CharacterCodes["i"] = 105] = "i"; - CharacterCodes[CharacterCodes["j"] = 106] = "j"; - CharacterCodes[CharacterCodes["k"] = 107] = "k"; - CharacterCodes[CharacterCodes["l"] = 108] = "l"; - CharacterCodes[CharacterCodes["m"] = 109] = "m"; - CharacterCodes[CharacterCodes["n"] = 110] = "n"; - CharacterCodes[CharacterCodes["o"] = 111] = "o"; - CharacterCodes[CharacterCodes["p"] = 112] = "p"; - CharacterCodes[CharacterCodes["q"] = 113] = "q"; - CharacterCodes[CharacterCodes["r"] = 114] = "r"; - CharacterCodes[CharacterCodes["s"] = 115] = "s"; - CharacterCodes[CharacterCodes["t"] = 116] = "t"; - CharacterCodes[CharacterCodes["u"] = 117] = "u"; - CharacterCodes[CharacterCodes["v"] = 118] = "v"; - CharacterCodes[CharacterCodes["w"] = 119] = "w"; - CharacterCodes[CharacterCodes["x"] = 120] = "x"; - CharacterCodes[CharacterCodes["y"] = 121] = "y"; - CharacterCodes[CharacterCodes["z"] = 122] = "z"; - CharacterCodes[CharacterCodes["A"] = 65] = "A"; - CharacterCodes[CharacterCodes["B"] = 66] = "B"; - CharacterCodes[CharacterCodes["C"] = 67] = "C"; - CharacterCodes[CharacterCodes["D"] = 68] = "D"; - CharacterCodes[CharacterCodes["E"] = 69] = "E"; - CharacterCodes[CharacterCodes["F"] = 70] = "F"; - CharacterCodes[CharacterCodes["G"] = 71] = "G"; - CharacterCodes[CharacterCodes["H"] = 72] = "H"; - CharacterCodes[CharacterCodes["I"] = 73] = "I"; - CharacterCodes[CharacterCodes["J"] = 74] = "J"; - CharacterCodes[CharacterCodes["K"] = 75] = "K"; - CharacterCodes[CharacterCodes["L"] = 76] = "L"; - CharacterCodes[CharacterCodes["M"] = 77] = "M"; - CharacterCodes[CharacterCodes["N"] = 78] = "N"; - CharacterCodes[CharacterCodes["O"] = 79] = "O"; - CharacterCodes[CharacterCodes["P"] = 80] = "P"; - CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; - CharacterCodes[CharacterCodes["R"] = 82] = "R"; - CharacterCodes[CharacterCodes["S"] = 83] = "S"; - CharacterCodes[CharacterCodes["T"] = 84] = "T"; - CharacterCodes[CharacterCodes["U"] = 85] = "U"; - CharacterCodes[CharacterCodes["V"] = 86] = "V"; - CharacterCodes[CharacterCodes["W"] = 87] = "W"; - CharacterCodes[CharacterCodes["X"] = 88] = "X"; - CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; - CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; - CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; - CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; - CharacterCodes[CharacterCodes["at"] = 64] = "at"; - CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; - CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; - CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; - CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; - CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; - CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; - CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; - CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; - CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; - CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; - CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; - CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; - CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; - CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; - CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; - CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; - CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; - CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; - CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; - CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; - CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; - CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; - CharacterCodes[CharacterCodes["question"] = 63] = "question"; - CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; - CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; - CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; - CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; - CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; - CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; - CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; - CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; - CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; - })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); - var Extension; - (function (Extension) { - Extension["Ts"] = ".ts"; - Extension["Tsx"] = ".tsx"; - Extension["Dts"] = ".d.ts"; - Extension["Js"] = ".js"; - Extension["Jsx"] = ".jsx"; - Extension["Json"] = ".json"; - })(Extension = ts.Extension || (ts.Extension = {})); - var TransformFlags; - (function (TransformFlags) { - TransformFlags[TransformFlags["None"] = 0] = "None"; - TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; - TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; - TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; - TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; - TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; - TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; - TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; - TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; - })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); - var EmitFlags; - (function (EmitFlags) { - EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; - EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; - EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; - EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; - EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; - EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; - EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; - EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; - EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; - EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; - EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; - EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; - EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; - EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; - EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; - EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; - EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; - EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; - EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; - EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; - EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; - EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; - EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; - EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; - EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; - EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; - EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; - EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; - EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; - EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; - })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); - var ExternalEmitHelpers; - (function (ExternalEmitHelpers) { - ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; - ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; - ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; - ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; - ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; - ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; - ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; - ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; - ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; - ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; - ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; - ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; - ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; - ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; - })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); - var EmitHint; - (function (EmitHint) { - EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; - EmitHint[EmitHint["Expression"] = 1] = "Expression"; - EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; - EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; - })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; - ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; - ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; - ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; - ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); - var PragmaKindFlags; - (function (PragmaKindFlags) { - PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None"; - PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML"; - PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine"; - PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine"; - PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All"; - PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default"; - })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {})); function _contextuallyTypePragmas(args) { return args; } @@ -1618,8 +425,8 @@ var ts; return undefined; } ts.findLast = findLast; - function findIndex(array, predicate) { - for (var i = 0; i < array.length; i++) { + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -1627,6 +434,15 @@ var ts; return -1; } ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; function findMap(array, callback) { for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); @@ -1957,6 +773,23 @@ var ts; return false; } ts.some = some; + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; function concatenate(array1, array2) { if (!some(array2)) return array1; @@ -2147,6 +980,15 @@ var ts; return to; } ts.addRange = addRange; + function prependRange(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + to.unshift.apply(to, from); + return to; + } + ts.prependRange = prependRange; function pushIfUnique(array, toAdd, equalityComparer) { if (contains(array, toAdd, equalityComparer)) { return false; @@ -2344,17 +1186,18 @@ var ts; } ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { + var _a; var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { result.push(map ? map(value) : value); } return result; - var _b; } ts.arrayFrom = arrayFrom; function forEachEntry(map, callback) { + var _a; var iterator = map.entries(); - for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { var key = pair[0], value = pair[1]; var result = callback(value, key); if (result) { @@ -2362,19 +1205,18 @@ var ts; } } return undefined; - var _b; } ts.forEachEntry = forEachEntry; function forEachKey(map, callback) { + var _a; var iterator = map.keys(); - for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { var result = callback(key); if (result) { return result; } } return undefined; - var _b; } ts.forEachKey = forEachKey; function copyEntries(source, target) { @@ -2843,11 +1685,11 @@ var ts; comparer(a[key], b[key]); } ts.compareProperties = compareProperties; - function getDiagnosticFileName(diagnostic) { - return diagnostic.file ? diagnostic.file.fileName : undefined; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; } function compareDiagnostics(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -2875,90 +1717,6 @@ var ts; } return text1 ? 1 : -1; } - function normalizeSlashes(path) { - return path.replace(/\\/g, "/"); - } - ts.normalizeSlashes = normalizeSlashes; - function getRootLength(path) { - if (path.charCodeAt(0) === 47) { - if (path.charCodeAt(1) !== 47) - return 1; - var p1 = path.indexOf("/", 2); - if (p1 < 0) - return 2; - var p2 = path.indexOf("/", p1 + 1); - if (p2 < 0) - return p1 + 1; - return p2 + 1; - } - if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92) - return 3; - } - if (path.lastIndexOf("file:///", 0) === 0) { - return "file:///".length; - } - var idx = path.indexOf("://"); - if (idx !== -1) { - return idx + "://".length; - } - return 0; - } - ts.getRootLength = getRootLength; - ts.directorySeparator = "/"; - var directorySeparatorCharCode = 47; - function getNormalizedParts(normalizedSlashedPath, rootLength) { - var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); - var normalized = []; - for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { - var part = parts_1[_i]; - if (part !== ".") { - if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { - normalized.pop(); - } - else { - if (part) { - normalized.push(part); - } - } - } - } - return normalized; - } - function normalizePath(path) { - return normalizePathAndParts(path).path; - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - var root = path.substr(0, rootLength); - var parts = getNormalizedParts(path, rootLength); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function pathEndsWithDirectorySeparator(path) { - return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; - } - ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; - function getDirectoryPath(path) { - return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function isUrl(path) { - return path && !isRootedDiskPath(path) && stringContains(path, "://"); - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -2990,6 +1748,10 @@ var ts; : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; } @@ -3009,181 +1771,351 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 && charCode <= 122) || + (charCode >= 65 && charCode <= 90); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58) + return start + 1; + if (ch0 === 37 && url.charCodeAt(start + 1) === 51) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 || ch2 === 65) + return start + 3; + } + return -1; + } + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + if (ch0 === 47 || ch0 === 92) { + if (path.charCodeAt(1) !== ch0) + return 1; + var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; + return p1 + 1; + } + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 || ch2 === 92) + return 3; + if (path.length === 2) + return 2; + } + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47) { + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); + } + return ~path.length; + } + return 0; + } + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function normalizePath(path) { + return resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; function isRootedDiskPath(path) { - return path && getRootLength(path) !== 0; + return getEncodedRootLength(path) > 0; } ts.isRootedDiskPath = isRootedDiskPath; + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); } ts.convertToRelativePath = convertToRelativePath; - function normalizedPathComponents(path, rootLength) { - var normalizedParts = getNormalizedParts(path, rootLength); - return [path.substr(0, rootLength)].concat(normalizedParts); + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); } - function getNormalizedPathComponents(path, currentDirectory) { - path = normalizeSlashes(path); + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); var rootLength = getRootLength(path); - if (rootLength === 0) { - path = combinePaths(normalizeSlashes(currentDirectory), path); - rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + function reducePathComponents(components) { + if (!some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); } - return normalizedPathComponents(path, rootLength); + return reduced; + } + ts.reducePathComponents = reducePathComponents; + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); } ts.getNormalizedPathComponents = getNormalizedPathComponents; function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); } ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getNormalizedPathFromPathComponents(pathComponents) { - if (pathComponents && pathComponents.length) { - return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); - } + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + if (pathComponents.length === 1) + return root; + return root + pathComponents.slice(1).join(ts.directorySeparator); } - ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; - function getNormalizedPathComponentsOfUrl(url) { - var urlLength = url.length; - var rootLength = url.indexOf("://") + "://".length; - while (rootLength < urlLength) { - if (url.charCodeAt(rootLength) === 47) { - rootLength++; - } - else { + ts.getPathFromPathComponents = getPathFromPathComponents; + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) break; - } } - if (rootLength === urlLength) { - return [url]; + if (start === 0) { + return toComponents; } - var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); - if (indexOfNextSlash !== -1) { - rootLength = indexOfNextSlash + 1; - return normalizedPathComponents(url, rootLength); - } - else { - return [url + ts.directorySeparator]; + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); } + return [""].concat(relative, components); } - function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { - if (isUrl(pathOrUrl)) { - return getNormalizedPathComponentsOfUrl(pathOrUrl); - } - else { - return getNormalizedPathComponents(pathOrUrl, currentDirectory); - } + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - directoryComponents.pop(); + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; } - var joinStartIndex; - for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { - break; - } - } - if (joinStartIndex) { - var relativePath = ""; - var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); - for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (directoryComponents[joinStartIndex] !== "") { - relativePath = relativePath + ".." + ts.directorySeparator; - } - } - return relativePath + relativePathComponents.join(ts.directorySeparator); - } - var absolutePath = getNormalizedPathFromPathComponents(pathComponents); - if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { - absolutePath = "file:///" + absolutePath; - } - return absolutePath; + return getPathFromPathComponents(pathComponents); } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function getRelativePath(path, directoryPath, getCanonicalFileName) { - var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ensurePathIsRelative(relativePath); + function ensurePathIsNonModuleName(path) { + return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path; } - ts.getRelativePath = getRelativePath; - function ensurePathIsRelative(path) { - return !pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsRelative = ensurePathIsRelative; - function getBaseFileName(path) { - if (path === undefined) { - return undefined; - } - var i = path.lastIndexOf(ts.directorySeparator); - return i < 0 ? path : path.substring(i + 1); + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; } ts.getBaseFileName = getBaseFileName; - function combinePaths(path1, path2) { - if (!(path1 && path1.length)) - return path2; - if (!(path2 && path2.length)) - return path1; - if (getRootLength(path2) !== 0) - return path2; - if (path1.charAt(path1.length - 1) === ts.directorySeparator) - return path1 + path2; - return path1 + ts.directorySeparator + path2; + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; } ts.combinePaths = combinePaths; + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 || ch === 92; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function removeTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) === ts.directorySeparator) { + if (hasTrailingDirectorySeparator(path)) { return path.substr(0, path.length - 1); } return path; } ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; function ensureTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) !== ts.directorySeparator) { + if (!hasTrailingDirectorySeparator(path)) { return path + ts.directorySeparator; } return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - function comparePaths(a, b, currentDirectory, ignoreCase) { + function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0; if (a === undefined) return -1; if (b === undefined) return 1; - a = removeTrailingDirectorySeparator(a); - b = removeTrailingDirectorySeparator(b); - var aComponents = getNormalizedPathComponents(a, currentDirectory); - var bComponents = getNormalizedPathComponents(b, currentDirectory); + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - var comparer = getStringComparer(ignoreCase); for (var i = 0; i < sharedLength; i++) { - var result = comparer(aComponents[i], bComponents[i]); + var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); if (result !== 0) { return result; } } return compareValues(aComponents.length, bComponents.length); } + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, getStringComparer(ignoreCase)); + } ts.comparePaths = comparePaths; function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } if (parent === undefined || child === undefined) return false; if (parent === child) return true; - parent = removeTrailingDirectorySeparator(parent); - child = removeTrailingDirectorySeparator(child); - if (parent === child) - return true; - var parentComponents = getNormalizedPathComponents(parent, currentDirectory); - var childComponents = getNormalizedPathComponents(child, currentDirectory); + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); if (childComponents.length < parentComponents.length) { return false; } - var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; + var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer; if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } @@ -3460,13 +2392,17 @@ var ts; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { - var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { - return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; + function isJavaScriptLike(scriptKind) { + return scriptKind === 1 || scriptKind === 2; + } function hasJavaScriptFileExtension(fileName) { return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } @@ -3488,13 +2424,6 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; - var ExtensionPriority; - (function (ExtensionPriority) { - ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; - ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; - ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; - ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; - })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -3525,7 +2454,7 @@ var ts; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; + var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx", ".json"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { var ext = extensionsToRemove_1[_i]; @@ -3546,9 +2475,14 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return (removeFileExtension(path) + newExtension); + return changeAnyExtension(path, newExtension, extensionsToRemove, false); } ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; function removeMinAndVersionNumbers(fileName) { var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); @@ -3596,13 +2530,6 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - var AssertionLevel; - (function (AssertionLevel) { - AssertionLevel[AssertionLevel["None"] = 0] = "None"; - AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; - AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; - AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; - })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -3807,6 +2734,10 @@ var ts; return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } ts.extensionIsTypeScript = extensionIsTypeScript; + function resolutionExtensionIsTypeScriptOrJson(ext) { + return extensionIsTypeScript(ext) || ext === ".json"; + } + ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); if (ext !== undefined) { @@ -3823,12 +2754,32 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPath(path) { + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive); + } var baseFileName = getBaseFileName(path); var extensionIndex = baseFileName.lastIndexOf("."); if (extensionIndex >= 0) { return baseFileName.substring(extensionIndex); } + return ""; } ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -3921,12 +2872,12 @@ var ts; ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; ts.missingFileModifiedTime = new Date(0); function createPollingIntervalBasedLevels(levels) { + var _a; return _a = {}, _a[PollingInterval.Low] = levels.Low, _a[PollingInterval.Medium] = levels.Medium, _a[PollingInterval.High] = levels.High, _a; - var _a; } var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); @@ -4199,11 +3150,6 @@ var ts; var isNode4OrLater = nodeVersion >= 4; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - var FileSystemEntryKind; - (function (FileSystemEntryKind) { - FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; - FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; - })(FileSystemEntryKind || (FileSystemEntryKind = {})); var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; var tscWatchFile = process.env.TSC_WATCHFILE; var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY; @@ -4243,6 +3189,7 @@ var ts; readDirectory: readDirectory, getModifiedTime: getModifiedTime, createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : undefined, getMemoryUsage: function () { if (global.gc) { global.gc(); @@ -4615,6 +3562,11 @@ var ts; hash.update(data); return hash.digest("hex"); } + function createSHA256Hash(data) { + var hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -4917,7 +3869,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5394,6 +4346,7 @@ var ts; Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5577,6 +4530,17 @@ var ts; Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5675,6 +4639,7 @@ var ts; Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5738,6 +4703,12 @@ var ts; Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), }; })(ts || (ts = {})); var ts; @@ -5971,7 +4942,7 @@ var ts; if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 294 && node._children.length > 0) { + if (node.kind === 298 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -6146,12 +5117,12 @@ var ts; case 159: case 162: case 163: - case 281: + case 283: case 234: case 204: case 235: case 236: - case 291: + case 295: case 233: case 153: case 154: @@ -6159,6 +5130,9 @@ var ts; case 156: case 191: case 192: + case 291: + case 296: + case 287: return true; default: ts.assertTypeIsNever(node); @@ -6181,6 +5155,12 @@ var ts; case 243: case 242: case 213: + case 234: + case 233: + case 238: + case 236: + case 235: + case 237: return true; default: return false; @@ -6192,13 +5172,7 @@ var ts; } ts.isAnyImportOrReExport = isAnyImportOrReExport; function getEnclosingBlockScopeContainer(node) { - var current = node.parent; - while (current) { - if (isBlockScope(current, current.parent)) { - return current; - } - current = current.parent; - } + return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function declarationNameToString(name) { @@ -6308,6 +5282,8 @@ var ts; case 155: case 156: case 236: + case 151: + case 150: errorNode = node.name; break; case 192: @@ -6335,6 +5311,10 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isJsonSourceFile(file) { + return file.scriptKind === 6; + } + ts.isJsonSourceFile = isJsonSourceFile; function isConstEnumDeclaration(node) { return node.kind === 237 && isConst(node); } @@ -6646,6 +5626,23 @@ var ts; }); } ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.isObjectLiteralExpression(expression) && expression; + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral && + ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -6983,6 +5980,10 @@ var ts; return node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJsonFile(node) { + return node && !!(node.flags & 16777216); + } + ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { return node && !!(node.flags & 2097152); } @@ -7160,6 +6161,10 @@ var ts; } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { case 243: case 249: @@ -7169,12 +6174,13 @@ var ts; case 186: return node.parent; case 177: - return ts.cast(node.parent.parent, ts.isImportTypeNode); + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: - return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + return undefined; } } - ts.importFromModuleSpecifier = importFromModuleSpecifier; + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { case 243: @@ -7223,12 +6229,20 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 281 && + return node.kind === 283 && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 296 || node.kind === 291; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && @@ -7250,6 +6264,8 @@ var ts; return v && v.initializer; case 151: return node.initializer; + case 269: + return node.initializer; } } function getSingleVariableOfVariableStatement(node) { @@ -7263,9 +6279,9 @@ var ts; node.body.kind === 238 && node.body; } - function getJSDocCommentsAndTags(node) { + function getJSDocCommentsAndTags(hostNode) { var result; - getJSDocCommentsAndTagsWorker(node); + getJSDocCommentsAndTagsWorker(hostNode); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; @@ -7274,8 +6290,7 @@ var ts; if (parent.kind === 269 || parent.kind === 151 || getNestedModuleDeclaration(parent)) { getJSDocCommentsAndTagsWorker(parent); } - if (parent.parent && - (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { + if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) { getJSDocCommentsAndTagsWorker(parent.parent); } if (parent.parent && parent.parent.parent && @@ -7284,15 +6299,15 @@ var ts; getSourceOfDefaultedAssignment(parent.parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent.parent); } - if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 || - ts.isBinaryExpression(parent) && getSpecialPropertyAssignmentKind(parent) !== 0 || + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 || node.kind === 184 && node.parent && node.parent.kind === 215) { getJSDocCommentsAndTagsWorker(parent); } if (node.kind === 148) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -7318,7 +6333,10 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - var host = getJSDocHost(node); + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || @@ -7327,18 +6345,9 @@ var ts; host; return decl && ts.isFunctionLike(decl) ? decl : undefined; } - ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; function getJSDocHost(node) { - while (node.parent.kind === 284) { - if (node.parent.parent.kind === 292) { - node = node.parent.parent; - } - else { - node = node.parent.parent.parent; - } - } - ts.Debug.assert(node.parent.kind === 283); - return node.parent.parent; + return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent; } ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { @@ -7353,15 +6362,10 @@ var ts; } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282; + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || type && type.kind === 284; } ts.isRestParameter = isRestParameter; - var AssignmentKind; - (function (AssignmentKind) { - AssignmentKind[AssignmentKind["None"] = 0] = "None"; - AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; - AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; - })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); function getAssignmentTargetKind(node) { var parent = node.parent; while (true) { @@ -7484,8 +6488,14 @@ var ts; if (ts.isDeclaration(name.parent)) { return name.parent.name === name; } - var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + else if (ts.isQualifiedName(name.parent)) { + var tag = name.parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + } + else { + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + } default: return false; } @@ -7615,14 +6625,6 @@ var ts; return 2 <= token && token <= 7; } ts.isTrivia = isTrivia; - var FunctionFlags; - (function (FunctionFlags) { - FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; - FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; - FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; - })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { if (!node) { return 4; @@ -7770,11 +6772,6 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - var Associativity; - (function (Associativity) { - Associativity[Associativity["Left"] = 0] = "Left"; - Associativity[Associativity["Right"] = 1] = "Right"; - })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); var hasArguments = expression.kind === 187 && expression.arguments !== undefined; @@ -7835,7 +6832,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 297: + case 301: return 0; case 203: return 1; @@ -8146,8 +7143,8 @@ var ts; }; } ts.createTextWriter = createTextWriter; - function getResolvedExternalModuleName(host, file) { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { @@ -8158,12 +7155,13 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - function getExternalModuleNameFromPath(host, fileName) { + function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); - return ts.removeFileExtension(relativePath); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { @@ -8245,7 +7243,7 @@ var ts; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { - if (signature.parameters.length) { + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { var thisParameter = signature.parameters[0]; if (parameterIsThisKeyword(thisParameter)) { return thisParameter; @@ -8322,16 +7320,33 @@ var ts; } ts.getTypeAnnotationNode = getTypeAnnotationNode; function getEffectiveReturnTypeNode(node) { + if (ts.isJSDocSignature(node)) { + return node.type && node.type.typeExpression && node.type.typeExpression.type; + } return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getEffectiveTypeParameterDeclarations(node) { - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 285); + var templateTags = ts.flatMap(ts.filter(node.parent.tags, ts.isJSDocTemplateTag), function (tag) { return tag.typeParameters; }); + var templateTagNodes = templateTags; + templateTagNodes.pos = templateTagNodes.length > 0 ? ts.first(templateTagNodes).pos : node.pos; + templateTagNodes.end = templateTagNodes.length > 0 ? ts.last(templateTagNodes).end : node.end; + templateTagNodes.hasTrailingComma = false; + return templateTagNodes; + } + return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; + var tag = ts.find(ts.getJSDocTags(node), function (tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 && tag.parent.tags.some(isJSDocTypeAlias)); + }); + return (tag && tag.typeParameters) || ts.emptyArray; } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; function getEffectiveSetAccessorTypeAnnotationNode(node) { @@ -8956,12 +7971,6 @@ var ts; return accessKind(node) !== 0; } ts.isWriteAccess = isWriteAccess; - var AccessKind; - (function (AccessKind) { - AccessKind[AccessKind["Read"] = 0] = "Read"; - AccessKind[AccessKind["Write"] = 1] = "Write"; - AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; - })(AccessKind || (AccessKind = {})); function accessKind(node) { var parent = node.parent; if (!parent) @@ -9456,8 +8465,8 @@ var ts; break; case 71: return declaration; - case 293: - case 288: { + case 297: + case 292: { var name = declaration.name; if (name.kind === 145) { return name.right; @@ -9476,7 +8485,9 @@ var ts; return undefined; } } - case 292: + case 291: + return declaration.name; + case 296: return getNameOfJSDocTypedef(declaration); case 248: { var expression = declaration.expression; @@ -9564,7 +8575,9 @@ var ts; function getJSDocTags(node) { var tags = node.jsDocCache; if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); } return tags; } @@ -9674,6 +8687,10 @@ var ts; return node.kind === 159; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 156 || node.kind === 155; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isTypePredicateNode(node) { return node.kind === 160; } @@ -9799,7 +8816,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296) { + while (node.kind === 300) { node = node.expression; } return node; @@ -10146,85 +9163,93 @@ var ts; } ts.isBundle = isBundle; function isJSDocTypeExpression(node) { - return node.kind === 275; + return node.kind === 277; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 276; + return node.kind === 278; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 277; + return node.kind === 279; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 278; + return node.kind === 280; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 279; + return node.kind === 281; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 280; + return node.kind === 282; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 281; + return node.kind === 283; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 282; + return node.kind === 284; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 283; + return node.kind === 285; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 286; + return node.kind === 289; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 287; + return node.kind === 290; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocParameterTag(node) { - return node.kind === 288; + return node.kind === 292; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 289; + return node.kind === 293; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 290; + return node.kind === 294; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 291; + return node.kind === 295; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 292; + return node.kind === 296; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 293; + return node.kind === 297; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 293 || node.kind === 288; + return node.kind === 297 || node.kind === 292; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 284; + return node.kind === 286; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 291; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 287; + } + ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); (function (ts) { function isSyntaxList(n) { - return n.kind === 294; + return n.kind === 298; } ts.isSyntaxList = isSyntaxList; function isNode(node) { @@ -10346,10 +9371,11 @@ var ts; switch (kind) { case 152: case 157: + case 287: case 158: case 159: case 162: - case 281: + case 283: case 163: return true; default: @@ -10428,13 +9454,13 @@ var ts; || kind === 95 || kind === 131 || kind === 206 - || kind === 276 - || kind === 277 || kind === 278 || kind === 279 || kind === 280 || kind === 281 - || kind === 282; + || kind === 282 + || kind === 283 + || kind === 284; } function isTypeNode(node) { return isTypeNodeKind(node.kind); @@ -10621,8 +9647,8 @@ var ts; case 203: case 207: case 205: - case 297: - case 296: + case 301: + case 300: return true; default: return isUnaryExpressionKind(kind); @@ -10635,11 +9661,11 @@ var ts; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 296; + return node.kind === 300; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 295; + return node.kind === 299; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -10739,7 +9765,9 @@ var ts; || kind === 236 || kind === 147 || kind === 231 - || kind === 292; + || kind === 296 + || kind === 291 + || kind === 297; } function isDeclarationStatementKind(kind) { return kind === 233 @@ -10774,13 +9802,13 @@ var ts; || kind === 213 || kind === 218 || kind === 225 - || kind === 295 || kind === 299 - || kind === 298; + || kind === 303 + || kind === 302; } function isDeclaration(node) { if (node.kind === 147) { - return node.parent.kind !== 291 || ts.isInJavaScriptFile(node); + return node.parent.kind !== 295 || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -10858,15 +9886,15 @@ var ts; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isJSDocNode(node) { - return node.kind >= 275 && node.kind <= 293; + return node.kind >= 277 && node.kind <= 297; } ts.isJSDocNode = isJSDocNode; function isJSDocCommentContainingNode(node) { - return node.kind === 283 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node); + return node.kind === 285 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; function isJSDocTag(node) { - return node.kind >= 285 && node.kind <= 293; + return node.kind >= 288 && node.kind <= 297; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -10911,12 +9939,12 @@ var ts; case 231: case 233: case 236: - case 275: - case 278: - case 279: + case 277: case 280: case 281: case 282: + case 283: + case 284: return true; } return false; @@ -12546,11 +11574,10 @@ var ts; } } function scanJSDocToken() { + startPos = tokenPos = pos; if (pos >= end) { return token = 1; } - startPos = pos; - tokenPos = pos; var ch = text.charCodeAt(pos); pos++; switch (ch) { @@ -12678,16 +11705,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var SignatureFlags; - (function (SignatureFlags) { - SignatureFlags[SignatureFlags["None"] = 0] = "None"; - SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; - SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; - SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; - SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; - SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; - SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; - })(SignatureFlags || (SignatureFlags = {})); var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -13077,7 +12094,7 @@ var ts; return visitNode(cbNode, node.expression); case 252: return visitNodes(cbNode, cbNodes, node.decorators); - case 297: + case 301: return visitNodes(cbNode, cbNodes, node.elements); case 254: return visitNode(cbNode, node.openingElement) || @@ -13104,23 +12121,23 @@ var ts; visitNode(cbNode, node.expression); case 257: return visitNode(cbNode, node.tagName); - case 275: + case 277: return visitNode(cbNode, node.type); - case 279: - return visitNode(cbNode, node.type); - case 278: + case 281: return visitNode(cbNode, node.type); case 280: return visitNode(cbNode, node.type); - case 281: - return visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); case 282: return visitNode(cbNode, node.type); case 283: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 284: + return visitNode(cbNode, node.type); + case 285: return visitNodes(cbNode, cbNodes, node.tags); - case 288: - case 293: + case 292: + case 297: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -13129,17 +12146,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } + case 293: + return visitNode(cbNode, node.typeExpression); + case 294: + return visitNode(cbNode, node.typeExpression); case 289: - return visitNode(cbNode, node.typeExpression); - case 290: - return visitNode(cbNode, node.typeExpression); - case 286: return visitNode(cbNode, node.class); - case 291: + case 295: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 292: + case 296: if (node.typeExpression && - node.typeExpression.kind === 275) { + node.typeExpression.kind === 277) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -13147,7 +12164,16 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 284: + case 291: + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 287: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 286: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -13155,7 +12181,7 @@ var ts; } } return; - case 296: + case 300: return visitNode(cbNode, node.expression); } } @@ -13163,7 +12189,13 @@ var ts; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + var result; + if (languageVersion === 100) { + result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + } ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; @@ -13220,6 +12252,13 @@ var ts; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined); + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + return result_1; + } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); @@ -13235,23 +12274,54 @@ var ts; return isInvalid ? entityName : undefined; } Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function parseJsonText(fileName, sourceText) { - initializeState(sourceText, 2, undefined, 6); + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2; } + initializeState(sourceText, languageVersion, syntaxCursor, 6); sourceFile = createSourceFile(fileName, 2, 6, false); - var result = sourceFile; nextToken(); + var pos = getNodePos(); if (token() === 1) { + sourceFile.statements = createNodeArray([], pos, pos); sourceFile.endOfFileToken = parseTokenNode(); } - else if (token() === 17 || - lookAhead(function () { return token() === 9; })) { - result.jsonObject = parseObjectLiteralExpression(); + else { + var statement = createNode(215); + switch (token()) { + case 21: + statement.expression = parseArrayLiteralExpression(); + break; + case 101: + case 86: + case 95: + statement.expression = parseTokenNode(); + break; + case 38: + if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 56; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8: + case 9: + if (lookAhead(function () { return nextToken() !== 56; })) { + statement.expression = parseLiteralNode(); + break; + } + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); sourceFile.endOfFileToken = parseExpectedToken(1, ts.Diagnostics.Unexpected_token); } - else { - parseExpected(17); + if (setParentNodes) { + fixupParentReferences(sourceFile); } sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; clearState(); return result; } @@ -13274,9 +12344,11 @@ var ts; switch (scriptKind) { case 1: case 2: - case 6: contextFlags = 65536; break; + case 6: + contextFlags = 65536 | 16777216; + break; default: contextFlags = 0; break; @@ -14266,9 +13338,9 @@ var ts; return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(276); + var result = createNode(278); if (postFixEquals) { - return createJSDocPostfixType(280, result); + return createJSDocPostfixType(282, result); } else { nextToken(); @@ -14276,7 +13348,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(279); + var result = createNode(281); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -14290,18 +13362,18 @@ var ts; token() === 29 || token() === 58 || token() === 49) { - var result = createNode(277, pos); + var result = createNode(279, pos); return finishNode(result); } else { - var result = createNode(278, pos); + var result = createNode(280, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(281); + var result = createNodeWithJSDoc(283); nextToken(); fillSignature(56, 4 | 32, result); return finishNode(result); @@ -14323,12 +13395,12 @@ var ts; var dotdotdot = parseOptionalToken(24); var type = parseType(); if (dotdotdot) { - var variadic = createNode(282, dotdotdot.pos); + var variadic = createNode(284, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } if (token() === 58) { - return createJSDocPostfixType(280, type); + return createJSDocPostfixType(282, type); } return type; } @@ -14396,10 +13468,11 @@ var ts; signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - signature.type = parseReturnType(returnToken, !!(flags & 4)); - } - function parseReturnType(returnToken, isType) { - return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + if (shouldParseReturnType(returnToken, !!(flags & 4))) { + signature.type = parseTypeOrTypePredicate(); + return signature.type !== undefined; + } + return true; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36) { @@ -14621,6 +13694,9 @@ var ts; var node = createNode(172); parseExpected(19); node.type = parseType(); + if (!node.type) { + return undefined; + } parseExpected(20); return finishNode(node); } @@ -14629,7 +13705,12 @@ var ts; if (kind === 163) { parseExpected(94); } - fillSignature(36, 4, node); + if (!fillSignature(36, 4 | (sourceFile.languageVariant === 1 ? 8 : 0), node)) { + return undefined; + } + if (!node.parameters) { + return undefined; + } return finishNode(node); } function parseKeywordAndNoDot() { @@ -14782,13 +13863,13 @@ var ts; while (!scanner.hasPrecedingLineBreak()) { switch (token()) { case 51: - type = createJSDocPostfixType(279, type); + type = createJSDocPostfixType(281, type); break; case 55: if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createJSDocPostfixType(278, type); + type = createJSDocPostfixType(280, type); break; case 21: parseExpected(21); @@ -15229,7 +14310,9 @@ var ts; var node = createNodeWithJSDoc(192); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); + if (!fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node)) { + return undefined; + } if (!node.parameters) { return undefined; } @@ -17115,39 +16198,6 @@ var ts; function isImportMeta(node) { return ts.isMetaProperty(node) && node.keywordToken === 91 && node.name.escapedText === "meta"; } - var ParsingContext; - (function (ParsingContext) { - ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; - ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; - ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; - ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; - ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; - ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; - ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; - ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; - ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; - ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; - ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; - ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; - ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; - ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; - ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; - ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; - ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; - ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; - })(ParsingContext || (ParsingContext = {})); - var Tristate; - (function (Tristate) { - Tristate[Tristate["False"] = 0] = "False"; - Tristate[Tristate["True"] = 1] = "True"; - Tristate[Tristate["Unknown"] = 2] = "Unknown"; - })(Tristate || (Tristate = {})); var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { @@ -17162,7 +16212,7 @@ var ts; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(275, scanner.getTokenPos()); + var result = createNode(277, scanner.getTokenPos()); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17); result.type = doInsideOfContext(2097152, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -17182,6 +16232,7 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var _a; var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -17199,20 +16250,8 @@ var ts; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; - var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; - var JSDocState; - (function (JSDocState) { - JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; - JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; - JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; - })(JSDocState || (JSDocState = {})); - var PropertyLikeParse; - (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; - })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -17254,7 +16293,7 @@ var ts; case 57: if (state === 0 || state === 1) { removeTrailingNewlines(comments); - parseTag(indent); + addTag(parseTag(indent)); state = 0; margin = undefined; indent++; @@ -17318,12 +16357,28 @@ var ts; } } function createJSDocComment() { - var result = createNode(283, start); + var result = createNode(285, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } + function isNextNonwhitespaceTokenEndOfFile() { + while (true) { + nextJSDocToken(); + if (token() === 1) { + return true; + } + if (!(token() === 5 || token() === 4)) { + return false; + } + } + } function skipWhitespace() { + if (token() === 5 || token() === 4) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; + } + } while (token() === 5 || token() === 4) { nextJSDocToken(); } @@ -17352,8 +16407,7 @@ var ts; case "arg": case "argument": case "param": - addTag(parseParameterOrPropertyTag(atToken, tagName, 1, indent)); - return; + return parseParameterOrPropertyTag(atToken, tagName, 2, indent); case "return": case "returns": tag = parseReturnTag(atToken, tagName); @@ -17365,7 +16419,10 @@ var ts; tag = parseTypeTag(atToken, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName); + tag = parseTypedefTag(atToken, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(atToken, tagName, indent); break; default: tag = parseUnknownTag(atToken, tagName); @@ -17378,8 +16435,10 @@ var ts; if (!tag) { return; } - tag.comment = parseTagComments(indent + tag.end - tag.pos); - addTag(tag); + if (!tag.comment) { + tag.comment = parseTagComments(indent + tag.end - tag.pos); + } + return tag; } function parseTagComments(indent) { var comments = []; @@ -17436,12 +16495,15 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { - var result = createNode(285, atToken.pos); + var result = createNode(288, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } function addTag(tag) { + if (!tag) { + return; + } if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -17490,8 +16552,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 ? - createNode(288, atToken.pos) : - createNode(293, atToken.pos); + createNode(297, atToken.pos) : + createNode(292, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -17511,18 +16573,18 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name, target) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(275, scanner.getTokenPos()); + var typeLiteralExpression = createNode(277, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 288 || child.kind === 293) { + if (child.kind === 292 || child.kind === 297) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(284, start_2); + jsdocTypeLiteral = createNode(286, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; if (typeExpression.type.kind === 166) { jsdocTypeLiteral.isArrayType = true; @@ -17533,27 +16595,27 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289; })) { + if (ts.forEach(tags, function (t) { return t.kind === 293; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(289, atToken.pos); + var result = createNode(293, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 290; })) { + if (ts.forEach(tags, function (t) { return t.kind === 294; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(290, atToken.pos); + var result = createNode(294, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var result = createNode(286, atToken.pos); + var result = createNode(289, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); @@ -17581,30 +16643,23 @@ var ts; return node; } function parseClassTag(atToken, tagName) { - var tag = createNode(287, atToken.pos); + var tag = createNode(290, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); } - function parseTypedefTag(atToken, tagName) { + function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(292, atToken.pos); + var typedefTag = createNode(296, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 || !rightNode.body) { - typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); skipWhitespace(); + typedefTag.comment = parseTagComments(indent); typedefTag.typeExpression = typeExpression; + var end; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; @@ -17612,9 +16667,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(284, start_3); + jsdocTypeLiteral = createNode(286, start_3); } - if (child.kind === 290) { + if (child.kind === 294) { if (childTypeTag) { break; } @@ -17633,23 +16688,67 @@ var ts; typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; } } - return finishNode(typedefTag); - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(238, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); - return finishNode(jsDocNamespaceNode); + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23)) { + var jsDocNamespaceNode = createNode(238, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4; } - if (typeNameOrNamespaceName && flags & 4) { - typeNameOrNamespaceName.isInJSDocNamespace = true; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(true); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(atToken, tagName, indent) { + var callbackTag = createNode(291, atToken.pos); + callbackTag.atToken = atToken; + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var start = scanner.getStartPos(); + var jsdocSignature = createNode(287, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (token() === 57) { + nextJSDocToken(); + var tag = parseTag(indent); + if (tag && tag.kind === 293) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; } - return typeNameOrNamespaceName; } } function escapedTextsEqual(a, b) { @@ -17665,7 +16764,7 @@ var ts; return a.escapedText === b.escapedText; } function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(0); + return parseChildParameterOrPropertyTag(1); } function parseChildParameterOrPropertyTag(target, name) { var canParseTag = true; @@ -17675,7 +16774,8 @@ var ts; case 57: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 288 && + if (child && child.kind === 292 && + target !== 4 && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -17714,20 +16814,20 @@ var ts; var t; switch (tagName.escapedText) { case "type": - return target === 0 && parseTypeTag(atToken, tagName); + return target === 1 && parseTypeTag(atToken, tagName); case "prop": case "property": - t = 0; + t = 1; break; case "arg": case "argument": case "param": - t = 1; + t = 2 | 4; break; default: return false; } - if (target !== t) { + if (!(target & t)) { return false; } var tag = parseParameterOrPropertyTag(atToken, tagName, target, undefined); @@ -17759,7 +16859,7 @@ var ts; break; } } - var result = createNode(291, atToken.pos); + var result = createNode(295, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -17805,7 +16905,7 @@ var ts; var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); var result = createNode(71, pos); - result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); return result; @@ -18101,10 +17201,6 @@ var ts; } } } - var InvalidPosition; - (function (InvalidPosition) { - InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; - })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); @@ -18536,6 +17632,13 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, { name: "removeComments", type: "boolean", @@ -18786,6 +17889,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, { name: "listFiles", type: "boolean", @@ -19067,11 +18176,13 @@ var ts; function parseCommandLine(commandLine, readFile) { var options = {}; var fileNames = []; + var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, + projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -19179,6 +18290,26 @@ var ts; } return optionNameMap.get(optionName); } + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; function readConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; @@ -19213,69 +18344,84 @@ var ts; var _tsconfigRootOptions; function getTsconfigRootOptionsMap() { if (_tsconfigRootOptions === undefined) { - _tsconfigRootOptions = commandLineOptionsToMap([ - { - name: "compilerOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 - }, - { - name: "typingOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "typeAcquisition", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "extends", - type: "string" - }, - { - name: "files", - type: "list", - element: { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { name: "files", - type: "string" - } - }, - { - name: "include", - type: "list", - element: { + type: "list", + element: { + name: "files", + type: "string" + } + }, + { name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { + type: "list", + element: { + name: "include", + type: "string" + } + }, + { name: "exclude", - type: "string" - } - }, - ts.compileOnSaveCommandLineOption - ]); + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; } return _tsconfigRootOptions; } function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, undefined, undefined); + return convertToObjectWorker(sourceFile, errors, true, undefined, undefined); } ts.convertToObject = convertToObject; - function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.jsonObject) { - return {}; + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } - return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined); function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { - var result = {}; + var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; if (element.kind !== 269) { @@ -19295,16 +18441,18 @@ var ts; } var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { - result[keyText] = value; + if (returnValue) { + result[keyText] = value; + } if (jsonConversionNotifier && - (parentOption || knownOptions === knownRootOptions)) { + (parentOption || isRootOptionMap(knownOptions))) { var isValidOptionValue = isCompilerOptionsValue(option, value); if (parentOption) { if (isValidOptionValue) { jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); } } - else if (knownOptions === knownRootOptions) { + else if (isRootOptionMap(knownOptions)) { if (isValidOptionValue) { jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); } @@ -19318,7 +18466,7 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -19384,6 +18532,7 @@ var ts; return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } + ts.convertToObjectWorker = convertToObjectWorker; function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : @@ -19566,12 +18715,13 @@ var ts; var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); - options.configFilePath = configFileName; + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; return { options: options, fileNames: fileNames, + projectReferences: projectReferences, typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), raw: raw, errors: errors, @@ -19610,19 +18760,43 @@ var ts; createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } - else { - var outDir = raw.compilerOptions && raw.compilerOptions.outDir; - if (outDir) { - excludeSpecs = [outDir]; + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); } } if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + var references = []; + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + references.push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + result.projectReferences = references; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } return result; } function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { @@ -19730,7 +18904,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertToObjectWorker(sourceFile, errors, true, getTsconfigRootOptionsMap(), optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -19764,6 +18938,7 @@ var ts; return extendedConfigPath; } function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -19791,7 +18966,6 @@ var ts; mapPropertiesInRawIfNotUndefined("files"); } return extendedConfig; - var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { @@ -19816,7 +18990,7 @@ var ts; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function getDefaultCompilerOptions(configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {}; return options; @@ -19824,10 +18998,13 @@ var ts; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -19921,7 +19098,7 @@ var ts; validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { @@ -19954,8 +19131,12 @@ var ts; } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { + return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); + }); return { fileNames: literalFiles.concat(wildcardFiles), + projectReferences: projectReferences, wildcardDirectories: wildcardDirectories, spec: spec }; @@ -19970,20 +19151,10 @@ var ts; return diag === undefined; }); function createDiagnostic(message, spec) { - if (jsonSourceFile && jsonSourceFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { - var property = _a[_i]; - if (ts.isArrayLiteralExpression(property.initializer)) { - for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (ts.isStringLiteral(element) && element.text === spec) { - return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); - } - } - } - } - } - return ts.createCompilerDiagnostic(message, spec); + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + ts.createCompilerDiagnostic(message, spec); } } function specToDiagnostic(spec, allowTrailingRecursion) { @@ -20120,7 +19291,8 @@ var ts; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; })(Extensions || (Extensions = {})); function resolvedTypeScriptOnly(resolved) { if (!resolved) { @@ -20161,7 +19333,13 @@ var ts; function readJson(path, host) { try { var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; } catch (e) { return {}; @@ -20571,7 +19749,11 @@ var ts; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + var result = jsOnly ? + tryResolve(Extensions.JavaScript) : + (tryResolve(Extensions.TypeScript) || + tryResolve(Extensions.JavaScript) || + (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); @@ -20624,7 +19806,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); if (!directoryProbablyExists(parentOfCandidate, state.host)) { @@ -20692,6 +19874,10 @@ var ts; return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); } function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (extensions === Extensions.Json) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json"); + return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + } var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; @@ -20719,6 +19905,8 @@ var ts; return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); case Extensions.JavaScript: return tryExtension(".js") || tryExtension(".jsx"); + case Extensions.Json: + return tryExtension(".json"); } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); @@ -20770,8 +19958,11 @@ var ts; } else { var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string") { - subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js"), ".jsx") + ".d.ts"; + if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { + var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts"; } else { subModuleName = "index.d.ts"; @@ -20803,9 +19994,17 @@ var ts; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); if (!file) { - return undefined; + if (extensions === Extensions.TypeScript) { + file = tryReadPackageJsonFields(false, jsonContent, candidate, state); + if (!file) { + return undefined; + } + } + else { + return undefined; + } } var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); @@ -20833,6 +20032,8 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" || extension === ".jsx"; + case Extensions.Json: + return extension === ".json"; case Extensions.TypeScript: return extension === ".ts" || extension === ".tsx" || extension === ".d.ts"; case Extensions.DtsOnly: @@ -20898,7 +20099,7 @@ var ts; if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript) { + if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { @@ -21073,12 +20274,42 @@ var ts; } JsTyping.isTypingUpToDate = isTypingUpToDate; JsTyping.nodeCoreModuleList = [ - "buffer", "querystring", "events", "http", "cluster", - "zlib", "os", "https", "punycode", "repl", "readline", - "vm", "child_process", "url", "dns", "net", - "dgram", "fs", "path", "string_decoder", "tls", - "crypto", "stream", "util", "assert", "tty", "domain", - "constants", "process", "v8", "timers", "console" + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" ]; JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); function loadSafeList(host, safeListPath) { @@ -21204,8 +20435,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_1.config; + var result_2 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_2.config; if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; @@ -21228,16 +20459,6 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; - var PackageNameValidationResult; - (function (PackageNameValidationResult) { - PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; - PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; - PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; - PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; - PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; - })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); var maxPackageNameLength = 214; function validatePackageName(packageName) { if (!packageName) { @@ -21804,11 +21025,12 @@ var ts; }()); function getDefaultNPMLocation(processName) { if (path.basename(processName).indexOf("node") === 0) { - return "\"" + path.join(path.dirname(process.argv[0]), "npm") + "\""; - } - else { - return "npm"; + var npmPath = "\"" + path.join(path.dirname(process.argv[0]), "npm") + "\""; + if (fs.existsSync(npmPath)) { + return npmPath; + } } + return "npm"; } function loadTypesRegistryFile(typesRegistryFilePath, host, log) { if (!host.fileExists(typesRegistryFilePath)) { @@ -21984,5 +21206,3 @@ var ts; })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); - -//# sourceMappingURL=typingsInstaller.js.map diff --git a/lib/watchGuard.js b/lib/watchGuard.js new file mode 100644 index 00000000000..4048f128878 --- /dev/null +++ b/lib/watchGuard.js @@ -0,0 +1,27 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +"use strict"; +if (process.argv.length < 3) { + process.exit(1); +} +var directoryName = process.argv[2]; +var fs = require("fs"); +try { + var watcher = fs.watch(directoryName, { recursive: true }, function () { return ({}); }); + watcher.close(); +} +catch (_a) { } +process.exit(0); diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index 67b76930ca9..b92e4727075 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "“{0}”的所有声明必须具有相同的修饰符。", "All_declarations_of_0_must_have_identical_type_parameters_2428": "“{0}”的所有声明都必须具有相同的类型参数。", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有声明必须是连续的。", + "All_destructured_elements_are_unused_6198": "未取消使用任何解构元素。", "All_imports_in_import_declaration_are_unused_6192": "未使用导入声明中的所有导入。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允许从不带默认输出的模块中默认输入。这不会影响代码发出,只是类型检查。", "Allow_javascript_files_to_be_compiled_6102": "允许编译 JavaScript 文件。", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "不能调用可能是 \"null\" 的对象。", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "不能调用可能是 \"null\" 或“未定义”的对象。", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "不能调用可能是“未定义”的对象。", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "无法为项目“{0}”添加前缀,因为它未设置 \"outFile\"", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "提供 \"--isolatedModules\" 标记时无法重新导出类型。", "Cannot_read_file_0_Colon_1_5012": "无法读取文件“{0}”: {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "无法重新声明块范围变量“{0}”。", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "编译给定了其配置文件路径或带 \"tsconfig.json\" 的文件夹路径的项目。", "Compiler_option_0_expects_an_argument_6044": "编译器选项“{0}”需要参数。", "Compiler_option_0_requires_a_value_of_type_1_5024": "编译器选项“{0}”需要类型 {1} 的值。", + "Composite_projects_may_not_disable_declaration_emit_6304": "复合项目可能不会禁用声明发出。", "Computed_property_names_are_not_allowed_in_enums_1164": "枚举中不允许计算属性名。", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "含字符串值成员的枚举中不允许使用计算值。", "Concatenate_and_emit_output_to_single_file_6001": "连接输出并将其发出到单个文件。", @@ -271,9 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生类的构造函数必须包含 \"super\" 调用。", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含文件,并且无法确定根目录,正在跳过在 \"node_modules\" 文件夹中查找。", "Convert_all_constructor_functions_to_classes_95045": "将所有构造函数都转换为类", + "Convert_all_require_to_import_95048": "将所有 \"require\" 转换为 \"import\"", "Convert_all_to_default_imports_95035": "全部转换为默认导入", "Convert_function_0_to_class_95002": "将函数“{0}”转换为类", "Convert_function_to_an_ES2015_class_95001": "将函数转换为 ES2015 类", + "Convert_require_to_import_95047": "将 \"require\" 转换为 \"import\"", "Convert_to_ES6_module_95017": "转换为 ES6 模块", "Convert_to_default_import_95013": "转换为默认导入", "Corrupted_locale_file_0_6051": "区域设置文件 {0} 已损坏。", @@ -326,8 +331,8 @@ "Duplicate_label_0_1114": "标签“{0}”重复。", "Duplicate_number_index_signature_2375": "数字索引签名重复。", "Duplicate_string_index_signature_2374": "字符串索引签名重复。", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "面向 ECMAScript 2015 模块时,不能使用动态导入。", "Dynamic_import_cannot_have_type_arguments_1326": "动态导入不能含有类型参数", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "仅当 \"--module\" 标志为 \"commonjs\" 或 \"esNext\" 时,才支持动态导入。", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "动态导入必须具有一个说明符作为参数。", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "动态导入的说明符类型必须是 \"string\",但此处类型是 \"{0}\"。", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "元素隐式具有 \"any\" 类型,因为索引表达式的类型不为 \"number\"。", @@ -336,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "发出包含源映射而非包含单独文件的单个文件。", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "在单个文件内发出源以及源映射;需要设置 \"--inlineSourceMap\" 或 \"--sourceMap\"。", "Enable_all_strict_type_checking_options_6180": "启用所有严格类型检查选项。", + "Enable_project_compilation_6302": "启用项目编译", "Enable_strict_checking_of_function_types_6186": "对函数类型启用严格检查。", "Enable_strict_checking_of_property_initialization_in_classes_6187": "启用类中属性初始化的严格检查。", "Enable_strict_null_checks_6113": "启用严格的 NULL 检查。", @@ -397,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "文件“{0}”的扩展名不受支持,正在跳过。", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "不支持文件“{0}”的扩展名。唯一支持的扩展名为 {1}。", "File_0_is_not_a_module_2306": "文件“{0}”不是模块。", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "文件“{0}”不在项目文件列表中。项目必须列出的所有文件,或使用“包含”模式。", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "文件“{0}”不在 \"rootDir\"“{1}”下。\"rootDir\" 应包含所有源文件。", "File_0_not_found_6053": "找不到文件“{0}”。", "File_change_detected_Starting_incremental_compilation_6032": "检测到文件更改。正在启动增量编译...", @@ -461,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在环境枚举声明中,成员初始化表达式必须是常数表达式。", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在包含多个声明的枚举中,只有一个声明可以省略其第一个枚举元素的初始化表达式。", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 \"const\" 枚举声明中,成员初始化表达式必须是常数表达式。", + "Include_modules_imported_with_json_extension_6197": "包括通过 \".json\" 扩展导入的模块", "Index_signature_in_type_0_only_permits_reading_2542": "类型“{0}”中的索引签名仅允许读取。", "Index_signature_is_missing_in_type_0_2329": "类型“{0}”中缺少索引签名。", "Index_signatures_are_incompatible_2330": "索引签名不兼容。", @@ -559,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== 模块名“{0}”已成功解析为“{1}”。========", "Module_resolution_kind_is_not_specified_using_0_6088": "未指定模块解析类型,正在使用“{0}”。", "Module_resolution_using_rootDirs_has_failed_6111": "使用 \"rootDirs\" 的模块解析失败。", + "Move_to_a_new_file_95049": "移动到新的文件", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允许使用多个连续的数字分隔符。", "Multiple_constructor_implementations_are_not_allowed_2392": "不允许存在多个构造函数实现。", "NEWLINE_6061": "换行符", @@ -600,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", "Options_Colon_6027": "选项:", "Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。", + "Output_file_0_from_project_1_does_not_exist_6309": "来自项目“{1}”的输出文件“{0}”不存在", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "未从源文件“{1}”生成输出文件“{0}”。", "Overload_signature_is_not_compatible_with_function_implementation_2394": "重载签名与函数实现不兼容。", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "重载签名必须都是抽象的或都是非抽象的。", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "重载签名必须全部为环境签名或非环境签名。", @@ -645,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "属于编译一部分的已生成文件的打印名称。", "Print_the_compiler_s_version_6019": "打印编译器的版本。", "Print_this_message_6017": "打印此消息。", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "项目引用不能形成环形图。检测到循环: {0}", + "Projects_to_reference_6300": "要引用的项目", "Property_0_does_not_exist_on_const_enum_1_2479": "\"const\" 枚举“{1}”上不存在属性“{0}”。", "Property_0_does_not_exist_on_type_1_2339": "类型“{1}”上不存在属性“{0}”。", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "类型“{1}”上不存在属性“{0}”。是否忘记使用 \"await\"?", @@ -692,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "对具有隐式 \"any\" 类型的表达式和声明引发错误。", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "在带隐式“any\" 类型的 \"this\" 表达式上引发错误。", "Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "引用的项目“{0}”必须拥有设置 \"composite\": true。", + "Remove_all_unreachable_code_95051": "删除所有无法访问的代码", "Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明", + "Remove_destructuring_90009": "删除解构", "Remove_import_from_0_90005": "从“{0}”删除导入", + "Remove_unreachable_code_95050": "删除无法访问的代码", "Replace_import_with_0_95015": "用“{0}”替换导入。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "在函数中的所有代码路径并非都返回值时报告错误。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "报告 switch 语句中遇到 fallthrough 情况的错误。", @@ -801,6 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "配置文件“{0}”中的 \"files\" 列表为空。", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "承诺的 \"then\" 方法的第一个参数必须是回调。", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全局类型 \"JSX.{0}\" 不可具有多个属性。", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "\"import.meta\" 元属性仅允许对 \"target\" 和 \"module\" 编译器选项使用 \"ESNext\"。", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "“{0}”的推断类型引用不可访问的“{1}”类型。需要类型批注。", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "\"for...in\" 语句的左侧不能为析构模式。", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "\"for...in\" 语句的左侧不能使用类型批注。", @@ -1013,6 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" 只能在 .ts 文件中使用。", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "指定了 \"paths“ 选项,正在查找模式以匹配模块名“{0}”。", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "\"readonly\" 修饰符仅可出现在属性声明或索引签名中。", + "require_call_may_be_converted_to_an_import_80005": "可将“要求”调用转换为导入。", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "设置了 \"rootDirs\" 选项,可将其用于解析相对模块名称“{0}”。", "super_can_only_be_referenced_in_a_derived_class_2335": "只能在派生类中引用 \"super\"。", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "仅可在派生类或对象文字表达式的成员中引用 \"super\"。", diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index aa2d1eac0eb..f250984e6f2 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -117,6 +117,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾詞。", "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。", + "All_destructured_elements_are_unused_6198": "不會使用所有未經結構化的項目。", "All_imports_in_import_declaration_are_unused_6192": "匯入宣告中的所有匯入皆未使用。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允許從沒有預設匯出的模組進行預設匯入。這不會影響程式碼發出,僅為類型檢查。", "Allow_javascript_files_to_be_compiled_6102": "允許編譯 JavaScript 檔案。", @@ -220,6 +221,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "無法叫用可能為 'null' 的物件。", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "無法叫用可能為 'null' 或 'undefined' 的物件。", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "無法叫用可能為 'undefined' 的物件。", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "因為專案 '{0}' 未設定 'outFile',所以無法於其前面加上任何內容", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "如有提供 '--isolatedModules' 旗標,即無法重新匯出類型。", "Cannot_read_file_0_Colon_1_5012": "無法讀取檔案 '{0}': {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "無法重新宣告區塊範圍變數 '{0}'。", @@ -260,6 +262,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "當路徑為專案組態檔或為 'tsconfig.json' 所在的資料夾時編譯專案。", "Compiler_option_0_expects_an_argument_6044": "編譯器選項 '{0}' 必須要有一個引數。", "Compiler_option_0_requires_a_value_of_type_1_5024": "編譯器選項 '{0}' 需要類型 {1} 的值。", + "Composite_projects_may_not_disable_declaration_emit_6304": "複合式專案可能未停用宣告發出。", "Computed_property_names_are_not_allowed_in_enums_1164": "列舉中不能有計算的屬性名稱。", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "具有字串值成員的列舉中不允許計算值。", "Concatenate_and_emit_output_to_single_file_6001": "串連並發出輸出至單一檔案。", @@ -271,11 +274,11 @@ "Constructors_for_derived_classes_must_contain_a_super_call_2377": "衍生類別的建構函式必須包含 'super' 呼叫。", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含檔案,因此無法決定根目錄,而將略過 'node_modules' 中的查閱。", "Convert_all_constructor_functions_to_classes_95045": "將所有建構函式轉換為類別", - "Convert_all_require_to_import_95048": "Convert all 'require' to 'import'", + "Convert_all_require_to_import_95048": "將所有 'require' 轉換至 'import'", "Convert_all_to_default_imports_95035": "全部轉換為預設匯入", "Convert_function_0_to_class_95002": "將函式 '{0}' 轉換為類別", "Convert_function_to_an_ES2015_class_95001": "將函式轉換為 ES2015 類別", - "Convert_require_to_import_95047": "Convert 'require' to 'import'", + "Convert_require_to_import_95047": "將 'require' 轉換至 'import'", "Convert_to_ES6_module_95017": "轉換為 ES6 模組", "Convert_to_default_import_95013": "轉換為預設匯入", "Corrupted_locale_file_0_6051": "地區設定檔 {0} 已損毀。", @@ -328,8 +331,8 @@ "Duplicate_label_0_1114": "標籤 '{0}' 重複。", "Duplicate_number_index_signature_2375": "數字索引簽章重複。", "Duplicate_string_index_signature_2374": "字串索引簽章重複。", - "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "以 ECMAScript 2015 模組為目標時,無法使用動態匯入。", "Dynamic_import_cannot_have_type_arguments_1326": "動態匯入不能有型別引數", + "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "只有當 '--module' 旗標是 'commonjs' 或 'esNext' 時,才支援動態匯入。", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動態匯入必須有一個指定名稱作為引數。", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動態匯入的指定名稱必須屬於類型 'string',但這裡的類型為 '{0}'。", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "因為索引運算式不屬於類型 'number',所以元素具有隱含 'any' 類型。", @@ -338,6 +341,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "發出單一檔案包含來源對應,而不要使用個別的檔案。", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "使用單一檔案發出來源與來源對應。必須設定 '--inlineSourceMap' 或 '--sourceMap'。", "Enable_all_strict_type_checking_options_6180": "啟用所有 Strict 類型檢查選項。", + "Enable_project_compilation_6302": "啟用專案編譯", "Enable_strict_checking_of_function_types_6186": "啟用嚴格檢查函式類型。", "Enable_strict_checking_of_property_initialization_in_classes_6187": "啟用類別中屬性初始化的 strict 檢查。", "Enable_strict_null_checks_6113": "啟用嚴格 null 檢查。", @@ -399,6 +403,7 @@ "File_0_has_an_unsupported_extension_so_skipping_it_6081": "因為不支援檔案 '{0}' 的副檔名,所以將其跳過。", "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "檔案 '{0}' 的附檔名不受支援。僅支援副檔名 {1}。", "File_0_is_not_a_module_2306": "檔案 '{0}' 不是模組。", + "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "檔案 '{0}' 不在專案檔案清單內。專案必須列出所有檔案,或使用 'include' 模式。", "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "檔案 '{0}' 不在 'rootDir' '{1}' 之下。'rootDir' 必須包含所有原始程式檔。", "File_0_not_found_6053": "找不到檔案 '{0}'。", "File_change_detected_Starting_incremental_compilation_6032": "偵測到檔案變更。正在啟動累加編譯...", @@ -463,6 +468,7 @@ "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在環境列舉宣告中,成員初始設定式必須是常數運算式。", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在具有多個宣告的列舉中,只有一個宣告可以在其第一個列舉項目中省略初始設定式。", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 'const' 列舉宣告中,成員初始設定式必須是常數運算式。", + "Include_modules_imported_with_json_extension_6197": "包含匯入有 '.json' 延伸模組的模組", "Index_signature_in_type_0_only_permits_reading_2542": "類型 '{0}' 中的索引簽章只允許讀取。", "Index_signature_is_missing_in_type_0_2329": "類型 '{0}' 中遺漏索引簽章。", "Index_signatures_are_incompatible_2330": "索引簽章不相容。", @@ -561,6 +567,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== 模組名稱 '{0}' 已成功解析為 '{1}'。========", "Module_resolution_kind_is_not_specified_using_0_6088": "未指定模組解析種類,將使用 '{0}'。", "Module_resolution_using_rootDirs_has_failed_6111": "使用 'rootDirs' 解析模組失敗。", + "Move_to_a_new_file_95049": "移至新行", "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允許多個連續的數字分隔符號。", "Multiple_constructor_implementations_are_not_allowed_2392": "不允許多個建構函式實作。", "NEWLINE_6061": "新行", @@ -602,8 +609,11 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "只有在提供選項 '--module' 或是 'target' 為 'ES2015' 或更高項目時,才可使用選項 'isolatedModules'。", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "必須指定 '--baseUrl' 選項才能使用選項 'paths'。", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "在命令列上,'project' 選項不得與原始程式檔並用。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "指定選項 '-resolveJsonModule' 時,不可沒有 'node' 模組解析策略。", "Options_Colon_6027": "選項:", "Output_directory_for_generated_declaration_files_6166": "所產生之宣告檔案的輸出目錄。", + "Output_file_0_from_project_1_does_not_exist_6309": "沒有來自專案 '{1}' 的輸出檔 '{0}'", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "輸出檔 '{0}' 並非從原始程式檔 '{1}' 建置。", "Overload_signature_is_not_compatible_with_function_implementation_2394": "多載簽章與函式實作不相容。", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "多載簽章必須全為抽象或非抽象。", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "多載簽章都必須是環境或非環境簽章。", @@ -647,6 +657,8 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "列印編譯時所產生之檔案部分的名稱。", "Print_the_compiler_s_version_6019": "列印編譯器的版本。", "Print_this_message_6017": "列印這則訊息。", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "專案參考不會形成循環圖。但偵測到循環: {0}", + "Projects_to_reference_6300": "專案至參考", "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 上並沒有屬性 '{0}'。", "Property_0_does_not_exist_on_type_1_2339": "類型 '{1}' 沒有屬性 '{0}'。", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "類型 '{1}' 不存在屬性 '{0}'。是否忘記要使用 'await'?", @@ -694,8 +706,12 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "當運算式及宣告包含隱含的 'any' 類型時顯示錯誤。", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "對具有隱含 'any' 類型的 'this' 運算式引發錯誤。", "Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "參考的專案 '{0}' 之設定 \"composite\" 必須為 true。", + "Remove_all_unreachable_code_95051": "移除所有無法連線的程式碼", "Remove_declaration_for_Colon_0_90004": "移除 '{0}' 的宣告", + "Remove_destructuring_90009": "移除解構", "Remove_import_from_0_90005": "從 '{0}' 移除匯入", + "Remove_unreachable_code_95050": "移除無法連線的程式碼", "Replace_import_with_0_95015": "以 '{0}' 取代匯入。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "當函式中的部分程式碼路徑並未傳回值時回報錯誤。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "回報 switch 陳述式內 fallthrough 案例的錯誤。", @@ -803,7 +819,7 @@ "The_files_list_in_config_file_0_is_empty_18002": "設定檔 '{0}' 中的 'files' 清單是空的。", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise 的 'then' 方法第一個參數必須為回撥。", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全域類型 'JSX.{0}' 的屬性不得超過一個。", - "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.", + "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "只有在為 'target' 及 'module' 編譯器選項使用 'ESNext' 時,才允許 'import.meta' 中繼屬性。", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' 的推斷型別參考了無法存取的 '{1}' 型別。必須有型別註解。", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 陳述式的左側不得為解構模式。", "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 陳述式左側不得使用類型註釋。", @@ -1016,7 +1032,7 @@ "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' 只可用於 .ts 檔案中。", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 選項已指定,將尋找符合模組名稱 '{0}' 的模式。", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾詞只能出現在屬性宣告或索引簽章。", - "require_call_may_be_converted_to_an_import_80005": "'require' call may be converted to an import.", + "require_call_may_be_converted_to_an_import_80005": "'require' 呼叫可能會轉換為匯入。", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 選項已設定。該選項將用於解析相對的模組名稱 '{0}'。", "super_can_only_be_referenced_in_a_derived_class_2335": "只有衍生類別中才可參考 'super'。", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "只有在衍生類別或物件常值運算式的成員中才可參考 'super'。",